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"))

```
You can use `map` and then `head`.

```
def map[S](f: (T) ⇒ S)(implicit executor: ExecutionContext): Future[S]

```

> 
> Creates a new future by applying a function to the successful result of this future. If this future is completed with an exception then the new future will also contain this exception.
> 
> 
> 

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

```

Caller of this dao can handle `Success` and `Failure` 

```
future.onComplete( {
  case Success(result) => ..
  case Failure(err) => .. //if head is empty you'll get java.util.NoSuchElementException
}

```