Question: So... lets say I have a `Future[ List[ A ] ]` and what I want get is a `Future` containing the `first element` of the `list` that is contained by the `Future`.

Considering this is a part of the db access layer what can be the preferred way of doing this ?

```
def getFirstByName( name: String ): Future[ A ] = {
  val aListFuture = ...
  // somehow got the future of list of all A's for this name 
  // Now how do I return a Future[ A ] contaning the head of said list
}

```

The focus of this question is more on `Considering this is a part of the db access layer what can be the preferred way of doing this ?`.

we can do something like following `val aFuture = aListFuture.map(l => l.head)` but what if the list was empty ?

In this question what I am really looking for is "how to design a predictable solution?".

Is there any other choice than to gracefully fail with a domain specific exception ? If not than how do I implement such failure ?

I am currently using the following dirty trick for this,

```
def getFirstByName( name: String ): Future[ A ] = {
  // somehow got the future of list of all A's for this name
  val aListFuture = ...
  aListFuture map( _.head ) match {
    case Some( t: Try[ A ] ) => t match {
      case Success( a: A ) => Promise.successful( a ).future
      case Failure( e: NoSuchElementException ) => Promise.failed( DbNotFound ).future
      case Failure( e ) => Promise.failed( e ).future
    }
    case _ => Promise.failed( new Exception( "Some unexplained exception" ) ).future
  }
}

```

Answer: 
Try this:

```
val futureOfHead = aListFuture.map (_.head)

```

For case when future returns empty list you may provide default value:

```
val DefaultValue = ...
val futureOfHead = aListFuture.map (_.headOption.getOrElse(DefaultValue))

```

Another option:

```
val futureOfHead = aListFuture.map (_.headOption.getOrElse(throw new RuntimeException("db layer exception"))

```
All anwsers are true but there may be a less error prone solution like this if fits to your problem:

```
val aListFuture = futureList.map(l => l.headOption)

```

which returns a Future[Option[A]] than can be checked by pattern matching.

Also, if you want and have a default value for this you can use:

```
val aListFuture = futureList.map(l => l.headOption.getOrElse(""))

```