ps0604
ps0604

Reputation: 1071

Future does not compile with Success and Failure

Why this does not compile? I get the following error in the Success and Failure lines:

constructor cannot be instantiated to expected type; found : scala.util.Success[T] required: Int

And the code:

    val future = Future { 1 }
    future.map { 
       case Success(s) => s
       case Failure(f) => 0
    }

Upvotes: 0

Views: 808

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Because map of a Future[Int] expects a function with domain Int, but instead you are trying to pass some function with domain Try[Int] into it.

The syntactically closest thing that works is onComplete:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Try, Success, Failure}

val future = Future { 1 }
future.onComplete { 
   case Success(s) => s
   case Failure(f) => 0
}

However, this is probably not what you want, because the expressions s and 0 don't do anything, they are therefore not very interesting callbacks. Instead, you probably either want to transform the result:

future.transform {
  case Success(s) => Success(s)
  case Failure(f) => Success(0)
}

or recover from the failure with a 0:

future.recover {
  case f: Exception => 0
}

Upvotes: 3

Emiliano Martinez
Emiliano Martinez

Reputation: 4133

Are you trying to do something like:

 val future = Future {
      1
    }
    future onComplete  {
      case Success(s) => s
      case Failure(f) => 0
    }

Upvotes: 1

Related Questions