I'm reading up on Java's Play framework but don't have much experience in Java. Can someone please explain this
Promise<Double> promiseOfPIValue = computePIAsynchronously();
Promise<Result> promiseOfResult = promiseOfPIValue.map(
new Function<Double,Result>() {
public Result apply(Double pi) {
return ok("PI value computed: " + pi);
}
}
);
I get that they're creating a promise promiseOfPiValue
that's supposed to compute a double asynchronously. Then, they call map
on that instance of promise to which they're passing a new instance of Function
as an argument, which has implemented a the apply
method.
The map part is where I get lost - how does the map method work? It looks like its returning a new promise of type Result
, but what's the logic of calling the apply
method inside an implementation of Function
?
From play documentation:
Maps this promise to a promise of type
B
. The functionfunction
is applied as soon as the promise is redeemed.
The function:
new Function<Double,Result>() {
public Result apply(Double pi) {
return ok("PI value computed: " + pi);
}
}
will convert the pi
value of type Double
to Result
using ok()
function defined in Controller
as soon as computePIAsynchronously
is finished.
but what's the logic of calling the apply method inside an implementation of Function?
This is the beauty of Promises
and Scala
. Scala promise framework will make sure the function is applied when promise is redeemed. If you want to read up on this topic, I suggest grabbing sources and documentation of scala.concurrent.ExecutionContext
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With