斯卡拉未来不值得期待?

时间:2014-03-24 22:58:44

标签: scala future

我正在尝试使用scala Futures从网络服务密钥/值存储实现线程批量获取。

大致

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))

给我一​​个编译错误

[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))
                         ^
我做错了什么。
我正在关注文档:如何阻止结果
http://docs.scala-lang.org/overviews/core/futures.html

scala.concurrent.Future不是定义Awaitable?我该如何强迫它?

2 个答案:

答案 0 :(得分:5)

如果我修复了示例代码中的语法(通过将def的主体放入块中,并将future{ "network get request here" }替换为_ => Future{ "network get request here" }),则可以编译并运行。问题出在代码的其他部分。

答案 1 :(得分:1)

适合我。

$ 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)