Search code examples
scalafuture

Map value from a Future to Object and not Future[Object]


I have a function that return a Future[State] and another function that I need return a StateSimplified object

//class State
case class State(id: String, label: String, postalCode: String, extension: Long...)

//class StateSimplified
case class StateSimplified(id: String, label: String)

Now I have this function

def getSimple(relationId: Int): Future[StateSimplified] = {
  repository.findStateByRelationId(relationId).map(state => 
    StateSimplified(id = state.id, label = state.label))
}

The repository.findStateByRelationId(relationId: Int) is a function that find a state from a related table, that function returns a Future[State] The problem is that the I need a StateSimplified not a Future[StateSimplified] because the StateSimplified I need to put it in an other class

case class City(id: Int, name: String, population: Long,..., state: StateSimplified)

How can I map the result from repository.findStateByRelationId(relationId: Int) to a StateSimplified and not a Future[StateSimplified]

Edit: In this suggested question the title is How to wait for a Future but the answer mark as solution suggest that the function return a Future, and don't want to return Future in my function because later that object is going into another different one City have an attribute called state that is of type StateSimplified


Solution

  • As said in the comments, when you get a Future, you have 2 options:

    1. continue to work with it, using map, flatMap or other operations. All of this is non-blocking.
    2. wait for it to return a value. This is blocking.

    Most of the time you want to do (1) up until the main class of your application . In any decent web framework, you don't even need (2), the framework will handle that for you.

    Back to your case, this means that you should do something like this:

    val futureCity: Future[City] = getSimple(...).map { stateSimplified =>
      // Build or set in a City
      City(...)
    }
    
    // Then work with the Future[City] rather than the City directly using map or flatMap...