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?

Answers


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
@ 

Need Your Help

history.go(-1) behavior in different browsers

javascript cross-browser

Does history.go(-1); behaves same in all browsers? I am seeing different behavior across various browsers.

PHP Image upload issue

php

I upload an image from my site and it loads in a folder debatepic but by default the image is storing in not-webvisible status ,So everytime after upload i need to change the status as webvisible s...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.