R van Rijn
R van Rijn

Reputation: 909

Elegant way of getting the Int value form Future[Option[Int]]

Is there a more elegant way of getting the Int value from Future[Option[Int]] instead of using finalFuture.value.get.get.get?

This is what I have so far:

  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
            }

Upvotes: 0

Views: 265

Answers (3)

Lee
Lee

Reputation: 144136

You could nest the match:

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

Upvotes: 3

GClaramunt
GClaramunt

Reputation: 3158

You can use also the toOption of Try to get Option[Option[Int]] and then flatten to get Option[Int]

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

EDIT: That assuming you don't care about the stacktrace :)

Upvotes: 0

cdk
cdk

Reputation: 6778

You can use foreach to apply a A => Unit function to the value in Option[A], if it exists.

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

Upvotes: 1

Related Questions