I am trying to use scala Futures to implement a threaded bulk get from a network service key/value store.
roughly
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
def bulkGet(keys: List[String])
val listFut = keys.map( future{ "network get request here" } )
val values = Future.sequence(listFut)
Await.result(values, Duration(10, SECONDS))
gives me a compile error
[info] Compiling 1 Scala source to .../target/scala-2.10/classes...
[error] .... type mismatch;
[error] found : scala.concurrent.Future[List[String]]
[error] required: scala.concurrent.Awaitable[scala.concurrent.Future[List[String]]]
[error] Await.result(values, Duration(10, SECONDS))
^
what am I doing wrong.
I am following the docs re: how to block on a result
http://docs.scala-lang.org/overviews/core/futures.html
Is a scala.concurrent.Future not by definition Awaitable? How do I coerce it to be?
If I fix the syntax in your example code (by putting the body of the def
into a block, and replacing future{ "network get request here" }
with _ => Future{ "network get request here" }
), this compiles and works. The problem is in some other part of the code.
Works for me.
$ scala
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.{Duration, SECONDS}
def bulkGet(keys: List[String]) = {
val listFut = keys.map(_ => Future("network get request here"))
val values = Future.sequence(listFut)
Await.result(values, Duration(10, SECONDS))
}
// Exiting paste mode, now interpreting.
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.{Duration, SECONDS}
bulkGet: (keys: List[String])List[String]
scala> bulkGet(List("foo", "bar", "baz"))
res0: List[String] = List(network get request here, network get request here, network get request here)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With