Scala:返回Future[Boolean]的方法中的多个return语句
我想做这样的事Scala:返回Future[Boolean]的方法中的多个return语句,scala,concurrency,future,Scala,Concurrency,Future,我想做这样的事 def foo(s : String): Future[Boolean] = Future { val a = someLongRunningMethod if(!a) return false or throw some exception // what should i return //do some more thing val b= someMoreLongRunningMethod if(b)
def foo(s : String): Future[Boolean] = Future {
val a = someLongRunningMethod
if(!a)
return false or throw some exception // what should i return
//do some more thing
val b= someMoreLongRunningMethod
if(b)
return true
return false
}
但不能将return与boolean一起使用。我得到了类型不匹配错误
Error:(32, 12) type mismatch;
found : Boolean(false)
required: scala.concurrent.Future[Boolean]
return false
我是斯卡拉的新手。我使用的是foo方法。我不确定这是不是最好的使用方法。请建议我应该如何实现它
val r = foo("Nishant")
r.onComplete {
case Success(result) => {
//Do something with my list
println("success: " + result)
}
case Failure(exception) => {
//Do something with my error
println("failure")
}
}
val re = Await.result(r, 10 second)
在Scala中,块中的最后一个表达式是代码块或函数的返回值。关键字返回在scala中是可选的
请注意,只有当一个任务返回true时,我们才运行第二个任务。如果第一个任务返回false,那么我们就完成了。这意味着,作为决策者,第一项任务对于我们的计算来说非常重要
您的版本已修改:
def longRunning1: Boolean = ???
def longRunning2: Boolean = ???
import scala.concurrent.ExecutionContext.Implicits.global
def foo(s : String): Future[Boolean] = Future {
val a: Boolean = longRunning1
if(a) {
val b: Boolean = longRunning2
b
} else false
}
第1版:
同时运行未来(计算或长时间运行的方法),然后选择结果。这里,如果我们考虑或想要第一次计算的结果,则丢弃第二次计算的结果。
import scala.concurrent.ExecutionContext.Implicits.global
def foo(s: String): Future[Boolean] = {
val f1 = Future {
Thread.sleep(20000) //Just to simulate long running task
Random.nextBoolean()
}
val f2 = Future {
Thread.sleep(1000) //Just to simulate long running task
Random.nextBoolean()
}
(f1 zip f2) map {
case (false, _) => false
case (true, f2Result) => f2Result
case _ => false
}
}
第2版:
运行第一个方法,然后根据第一个方法的结果尝试依次运行第二个方法。使用map链接计算
import scala.concurrent.ExecutionContext.Implicits.global
def foo(s: String): Future[Boolean] = {
val f1 = Future {
Thread.sleep(20000) //Just to simulate long running task
Random.nextBoolean()
}
f1.map { result =>
if (result) result
else {
Thread.sleep(1000) //Just to simulate long running task
Random.nextBoolean()
}
}
}
您需要首先阅读一篇关于
Future
类型如何工作的教程(顺便说一句,使用这样的返回不是Scala idomatic)。我读了一些教程,但它们都有单个if/else块的示例。你能推荐一些好的教程吗?第2版..如果logRunningTash和logRunningTash都可以抛出异常,那么如何处理异常?当两个任务都依赖时,哪一个更好?即第二个任务需要第一个任务的输入?@NishantKumar让我用异常更新问题cases@NishantKumar版本:2比版本1好。从异常的角度来看,v1和v2都是好的