【问题标题】:Scala: Better way to handle Future.Filter.exists without any specific conditionsScala:在没有任何特定条件的情况下处理 Future.Filter.exists 的更好方法
【发布时间】:2019-02-13 09:29:41
【问题描述】:

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

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

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

def abc = filteredFuture.map( _ => {...})

【问题讨论】:

  • 另请注意,filter 将使 Future 失败(有一个非常通用的异常),因此这很可能不是您想要的。

标签: scala collections


【解决方案1】:

你可以替换:

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

与:

tryThis.filter(_.isDefined)

【讨论】:

  • 感谢_.isDefined@senjin.hajrulahovic,我多么愚蠢地写了这个_.exists(_ => true)
【解决方案2】:

最好的方法是像这样在Option 上调用map

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

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

请注意,如果原来的OptionNone,这将返回Future(None),而filter 将产生一个失败的异常,所以它们不会做同样的事情。

【讨论】:

    【解决方案3】:
    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…) }
    

    【讨论】:

    • 您可能应该解释一下您的两种解决方案会产生不同的结果。
    • @Tim Good call — 已修改。
    【解决方案4】:
    
      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 的建议

    【讨论】:

    • foreachandThen 如果没有返回值且只有副作用,似乎更合适。
    猜你喜欢
    • 2014-02-17
    • 2016-12-15
    • 1970-01-01
    • 2018-09-17
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多