问题
The introduction of CompletableFutures
in Java 8 brought to the language features available in the scala.concurrent.Future
such as monadic transformations.
What are the differences, and why a Scala developer should prefer Scala Futures over java 8
CompletableFuture
?Are there still good reasons to use the
scala.concurrent.Future
in Java throughakka.dispatch
bridge?
回答1:
What are the differences, and why a Scala developer should prefer Scala Futures over java 8 CompletableFuture ?
Rephrasing what @dk14 pointed out in comments I'd say that CompletableFuture
doesn't have idiomatic Scala api.
For scala developer the implications are:
- lack of for comprehensions due to fact that it does not follow Scala method conventions common for monadic types
- java-scala interop overhead needed when using big part of it's methods
It is also worth noting that java CompletableFuture
is not exactly equivalent of scala Future
. It is rather a fuse of scala Future
and Promise
.
Considering the cons listed above there isn't much sense in using CompletableFuture
in scala unless you are designing public api that should be seamlessly interoperable with java.
Are there still good reasons to use the scala.concurrent.Future in Java through akka.dispatch bridge?
I am particularly looking for reasons to use akka.dispatch in Java, if there are still any
Akka is build on top of scala and it sometimes uses scala Future
s. This means that in cases when you have some portion of code written in java it is worth to wrap it in scala api (with akka.dispatch
java api) to be able to easily use it with akka.
For example, you are implementing akka actor in java. When processing message you want to do some non-blocking reading that, when done, should produce result as a message to another actor.
What you could do is to put your I/O into java Callable, then use akka.dispatch.Futures#future to get scala Future
out of it, and then you could leverage akka pipe to make result of the future be delivered as a message to some actor.
来源:https://stackoverflow.com/questions/28588806/scala-futures-and-java-8-completablefuture