带有显式返回语句的scala Future

时间:2016-10-09 16:52:25

标签: scala future

这个问题不是关于重构函数以避免任何显式返回语句。

我需要使用显式return语句异步运行一个函数。例如:

import scala.concurrent._
import scala.concurrent.duration._

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def evaluate(): Future[Int] = Future {
   return 42
}


val t = Await.result(evaluate(), 1 second)

println(t)

(与amm一起运行)

如果我编译它,我会收到此错误:

future_return.sc:8: type mismatch;
 found   : Int(42)
 required: scala.concurrent.Future[Int]
   return 42
          ^
Compilation Failed

所以我的第一个问题是为什么这只是失败而只是

def evaluate() = Future { 42 }

有效吗?使用return可以绕过Future"关键字"是否有很大差异?在实际功能代码之前?

第二个问题:如何在保持return声明的同时使其发挥作用?

我尝试过像

这样的事情
return Future[Int] {42}

但我收到此错误

scala.runtime.NonLocalReturnControl
Exception in thread "main" java.util.concurrent.TimeoutException: Futures timed out after [1 second]

所以不确定我是否朝着正确的方向前进。

由于

1 个答案:

答案 0 :(得分:1)

错误很简单:42不是Future[Int]类型。要执行您想要执行的操作,请使用Future.successful(42)。这是创建包含Int的Success的简洁方法。我建议你复习monad的概念,如果你知道monad,请重新阅读Scala中的Futures。

你的错误相当普遍,我在Scala的早期阶段就用这样的东西挣扎了很多但是避免这些障碍的最好方法是清楚地理解这个理论,并了解Scala用来实现的所有工具它

编辑:避免在Scala中使用return

相关问题