Reputation: 13
I'm trying to use values generated by a Scala Future:
val x = for (i <- 0 until 100) yield Future(Random.nextInt(arraySize))
For each value of x, I want to index into an array:
val y = for (j <- x) yield myArray(j) // doesn't work
val y2 = x map (j => myArray(j)) // doesn't work
myArray
can only be accessed with an int. How is this done with Scala Futures?
Candidate solution:
val y3 = x.map{ future => future.map(j => myArray(j) }
Upvotes: 1
Views: 359
Reputation: 44908
Did you mean something like this:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._
import java.util.concurrent.ThreadLocalRandom
val arraySize = 100
val myArray: Vector[String] = Vector.fill(arraySize)("")
val x: Future[IndexedSeq[Int]] = Future.sequence((0 until 100).map{
i =>
Future(ThreadLocalRandom.current.nextInt(arraySize))
})
val y: Future[IndexedSeq[String]] = for {
indices <- x // Future's `map`
} yield for {
i <- indices // IndexedSeq's `map`
} yield myArray(i)
The last double for
-expression could also be rewritten as
x map (_ map myArray)
if you wanted it really terse.
Upvotes: 4