Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

functional programming - Future[Try[Book]] vs Future[Book] in Scala?

I was suggested to use Future[Book] rather than Future[Try[Book]] in a pull request review.

Why is that?

If I use Future[Book], then how I can convert Success or Failure. Is it not clear to me at all.

If we use Future[Book], we are completely losing the notion of success and failure in Scala.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Scala, the resulting value of a future is wrapped in either a Success or Failure type, which is a type of Try. Hence, the value in a Future is always an instance of one of the Try types: Success or Failure.

Since these are Try types, you can register a callback on a future which accepts a Try type. An example is to use the onComplete which takes a callback function of type Try[T] => U and returns a Unit.

import scala.util.{Success, Failure}

val f: Future[List[String]] = Future {
  session.getUserNamesFromDatabase
}

f onComplete {
  case Success(users) => for (user <- users) println(user)
  case Failure(t) => println("An error has occurred: " + t.getMessage)
}

The benefit of a callback on a future is that it can complete without blocking the client. So the callback can execute completely asynchronously.

Note: that the onComplete method has a unit return type. So it cannot be chained.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...