为什么我无法从Future返回None

时间:2018-04-19 09:39:34

标签: scala

为什么这段代码没有编译?

scala> import scala.concurrent.Future
import scala.concurrent.Future

scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global


scala> def fut:Future[Int] = {
     |
     |   val f1:Option[Int] = Future{ None }
     |    f1.map (x => {  //when f1 finishes, create another future
     |   println(x)
     |         x match {
     |    case Some(i) => {
     |            0 
     |          }
     |          case None => { 
     |             val f2 = Future{ 2 } 
     |             f2.map(x => 1) 
     |    }
     |        }
     |     })
     |  }
<console>:30: error: type mismatch;
 found   : scala.concurrent.Future[None.type]
 required: Option[Int]
         val f1:Option[Int] = Future{ None }
                                    ^
<console>:35: error: constructor cannot be instantiated to expected type;
 found   : Some[A]
 required: Int
         case Some(i) => {
              ^
<console>:38: error: pattern type is incompatible with expected type;
 found   : None.type
 required: Int
                case None => { //user doesn't exist. create the user in the database using another Future
                     ^
<console>:32: error: type mismatch;
 found   : Option[Any]
 required: scala.concurrent.Future[Int]
          f1.map (x => {  //when f1 finishes, create another future
                 ^

1 个答案:

答案 0 :(得分:1)

val f1:Option[Int] = Future{ None }

Future不是Option。你可能意味着

val f1: Future[Option[Int]] = Future.successful(None)
case Some(_) => 0
case None => aFuture

这也行不通。您必须在两个分支中返回Future[Int]。这也意味着flatMap而不是map

上的f1

总结

def fut: Future[Int] = {

    val f1: Future[Option[Int]] = Future.successful(None)

    f1.flatMap(x => { //when f1 finishes, create another future
      x match {
        case Some(i) => {
          Future.successful(0)
        }
        case None => {
          val f2 = Future.successful(2)
          f2.map(x => 1)
        }
      }
    })
  }