Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing value returned by scala futures

Tags:

scala

future

I am a newbie to scala futures and I have a doubt regarding the return value of scala futures.

So, generally syntax for a scala future is

 def downloadPage(url: URL) = Future[List[Int]] {   } 

I want to know how to access the List[Int] from some other method which calls this method.

In other words,

val result = downloadPage("localhost")  

then what should be the approach to get List[Int] out of the future ?

I have tried using map method but not able to do this successfully.`

like image 711
user1822249 Avatar asked Jul 18 '13 02:07

user1822249


1 Answers

The case of Success(listInt) => I want to return the listInt and I am not able to figure out how to do that.

The best practice is that you don't return the value. Instead you just pass the future (or a version transformed with map, flatMap, etc.) to everyone who needs this value and they can add their own onComplete.

If you really need to return it (e.g. when implementing a legacy method), then the only thing you can do is to block (e.g. with Await.result) and you need to decide how long to await.

like image 179
Alexey Romanov Avatar answered Oct 24 '22 20:10

Alexey Romanov