I'm learning about CompletableFuture
s.
I am not asking about the difference between thenApply()
and thenCompose()
. Instead, I want to ask about a code "scent" that doesn't feel right, and what might actually justify it.
From the usages of CompletableFuture
s I've seen so far, it seems you'd never have this:
CompletableFuture<String> foo = getSomething().thenApply((result) -> { ... });
Nor this:
String foo = getSomething().thenCompose((result) -> { ... });
To return a future, you have to use thenCompose()
, and otherwise thenApply()
.
From experience though, it seems weird that language didn't devise a way to eliminate making this unambiguous choice every time. For example, couldn't there have been a single method thenDo()
whose return type is inferred (during compile-time) from the return
within the lambda? It could then be given thenApply
or thenCompose
-like properties at compile-time as well.
But I'm sure there's a good reason for having separate methods, so I'd like to know why.
Is it because it's dangerous or not possible to infer return types from lambdas in Java? (I'm new to Java as well.)
Is it because there is a case in which a single method would indeed be ambiguous, and the only solution is to have separate methods? (I'm imagining maybe, nested
CompletableFuture
s or complicated interfaces and generics.) If so, can someone provide a clear example?Is it for some other reason or documented recommendation?