j3d
j3d

Reputation: 9724

Scala: How to print a List in a Future

Look at the following code snippet:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object Main extends App {

  ids.foreach { l => println(l.mkString(", ")) }
  for(l <- ids) println(l.mkString(", "))

  def ids = Future(List(1, 2, 3, 4))
}

Method ids returns a Future[List[Int]] and I want to print the values of the returned List:

ids.map { l => println(l.mkString(", ")) } // prints nothing
for(l <- ids) println(l.mkString(", "))    // prints nothing

The problem is that none of the statements above prints the content of the List returned by ids. Am I missing something?

Upvotes: 2

Views: 2302

Answers (1)

Hugh
Hugh

Reputation: 8932

Your statements aren't printing anything because your program is exiting before they run. If you wait for the Future to finish, you should see the values get printed out. See scala.concurrent.Await.result

E.g.

@ import scala.concurrent._, duration._, ExecutionContext.Implicits._
import scala.concurrent._, duration._, ExecutionContext.Implicits._
@ def ids = Future(List(1,2,3,4))
defined function ids
@ Await.result(ids.map(l => println(l.mkString(", "))), Duration.Inf)
1, 2, 3, 4
@ 

Upvotes: 6

Related Questions