Manu Chadha
Manu Chadha

Reputation: 16723

Why am I not able to return None from Future

Why does this code doesn't compile?

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
                 ^

Upvotes: 0

Views: 1664

Answers (1)

Thilo
Thilo

Reputation: 262504

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

A Future is not an Option. You probably meant

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

case Some(_) => 0
case None => aFuture

This won't work, either. You have to return a Future[Int] in both branches. That also implies flatMap instead of map on f1


In summary

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)
        }
      }
    })
  }

Upvotes: 1

Related Questions