Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Future not Awaitable?

Tags:

scala

future

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?

like image 932
Jake O Avatar asked Mar 24 '14 22:03

Jake O


2 Answers

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.

like image 90
Hugh Avatar answered Oct 19 '22 16:10

Hugh


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)
like image 1
Sudheer Aedama Avatar answered Oct 19 '22 17:10

Sudheer Aedama