获取Int值的优雅方式Future [Option [Int]]

时间:2014-06-12 19:15:18

标签: scala

是否有更优雅的方式从Int获取Future[Option[Int]]值,而不是使用finalFuture.value.get.get.get

这是我到目前为止所做的:

  val finalFuture: Future[Option[Int]] = result.contents

  finalFuture.onComplete {
              case Success(value) => println(s"Got the callback with value = ", finalFuture.value.get.get.get)
              case Failure(e) => e.printStackTrace
            }

3 个答案:

答案 0 :(得分:3)

你可以嵌套比赛:

finalFuture.onComplete {
  case Success(Some(value)) => println(s"Got the callback with value = ", value)
  case Success(None) => ()
  case Failure(e) => e.printStackTrace
}

答案 1 :(得分:1)

您可以使用foreachA => Unit函数应用于Option[A]中的值(如果存在)。

fut.onComplete {
  case Success(opt) => opt.foreach { val =>
    println(s"Got the callback with value = {}", val)
  }
  case Falure(ex) => ex.printStackTrace
}    

答案 2 :(得分:0)

您也可以使用toOption of Try获取Option [Option [Int]]然后展平以获得Option [Int]

def printVal(finalFuture: Future[Option[Int]] ) =  finalFuture.onComplete( 
    _.toOption.flatten.foreach(x=> println (s"got {}",x))
  )

编辑:假设你不关心堆栈跟踪:)

相关问题