ps0604 ps0604 - 7 days ago 5
Scala Question

Invoking Future method in a loop

Given the case class

Person
defined as:

case class Person ( first: String, middle: String, last: String )


And the case class
Band
that contains many
Person
s:

case class Band ( name: String, members: List[Person] )


What I need is to add the middle initial in Person for each member in the band, taking into account that the function
getMiddle
is actually a Future. This is my attempt:

case class Person ( first: String, middle: String, last: String )
case class Band ( name: String, members: List[Person] )

object TestFutures3 extends App {

val p1 = Person ( "David", "", "Gahan" )
val p2 = Person ( "Martin", "", "Gore" )
val band = Band ( "Depeche Mode", List(p1,p2) )

def getMiddle (name: String) = Future {
if (name == "Martin")
"L"
else
"X"
}

val membersWithMiddle = band.members.map {
p => Person(p.first, getMiddle(p.first).map(_), p.last)
}

println(membersWithMiddle)

Thread.sleep(5000)
}

Answer

You can either await the future, and assign the middle directly:

val middle = Await.result(getMiddle(p.first), Duration.Inf)
val x: Person = Person(p.first, middle, p.last)

Or you can return a future person:

val x: Future[Person] = getMiddle(p.first).map(middle => Person(p.first, middle, p.last)