Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...