Scala:我只有在前一次返回Some(x)时才需要执行操作。比使用下面的代码更好的方法是做什么
def tryThis: Future[Option[T]] = {...}
val filteredFuture = tryThis.filter(_.exists(_ => true))
def abc = filteredFuture.map( _ => {...})
最好的方法是在map
上调用Option
,如下所示:
tryThis.map(_.map(_ => {...}))
只有当Future
返回Some(x)
时才会调用该函数。结果是另一个Future[Option[U]]
,其中U
是你的功能的结果。
请注意,如果原始Future(None)
是Option
,这将返回None
,而filter
将生成失败的异常,因此他们不会做同样的事情。
def tryThis: Future[Option[T]] = {...}
// Resulting future will be failed if it a None
// and its type will be that of the expression in `x…`
def abc = tryThis collect { case Some(x) => x… }
// Resulting future will be a None if it was a None
// and a Some with the type of the expression in `x…`
def abc = tryThis map { _.map(x => x…) }
你可以替换:
tryThis.filter(_.exists(_ => true))
有:
tryThis.filter(_.isDefined)
import scala.concurrent.ExecutionContext.Implicits.global
def square(a: Int): Future[Option[Int]] = Future.successful(Option(a * a))
def printResult(a: Int): Unit = println(s"Result: $a")
square(2).foreach(_.map(printResult))
编辑:根据@Thilo的建议