stats_man97531
stats_man97531

Reputation: 13

In Scala, how do you use the value of the Future before it's used?

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

Answers (1)

Andrey Tyukin
Andrey Tyukin

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

Related Questions