Scala Futures and java 8 CompletableFuture

后端 未结 1 1192
情书的邮戳
情书的邮戳 2021-02-02 14:04

The introduction of CompletableFutures in Java 8 brought to the language features available in the scala.concurrent.Future such as monadic transformati

相关标签:
1条回答
  • 2021-02-02 14:19

    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 Futures. 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.

    0 讨论(0)
提交回复
热议问题