Scala:在没有任何特定条件的情况下处理Future.Filter.exists的更好方法

问题描述 投票:1回答:4

Scala:我只有在前一次返回Some(x)时才需要执行操作。比使用下面的代码更好的方法是做什么

def tryThis: Future[Option[T]] = {...}

val filteredFuture = tryThis.filter(_.exists(_ => true))

def abc = filteredFuture.map( _ => {...})
scala collections
4个回答
2
投票

最好的方法是在map上调用Option,如下所示:

tryThis.map(_.map(_ => {...}))

只有当Future返回Some(x)时才会调用该函数。结果是另一个Future[Option[U]],其中U是你的功能的结果。

请注意,如果原始Future(None)Option,这将返回None,而filter将生成失败的异常,因此他们不会做同样的事情。


2
投票
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…) }

0
投票

你可以替换:

tryThis.filter(_.exists(_ => true))

有:

tryThis.filter(_.isDefined)

0
投票

  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的建议

© www.soinside.com 2019 - 2024. All rights reserved.