Play! Java example Java

I read on the Java Play platform, but do not have much experience working in Java. Can someone 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 understand that they are creating a promise promiseOfPiValue that should calculate double asynchronously. They then call map on this promise instance, to which they pass the new Function instance as the argument that the apply method implemented.

The part of the map where I get lost - how does the map method work? It looks like it is returning a new promise of type Result , but what is the logic of invoking the apply method inside the Function implementation?

+6
source share
1 answer

From the documentation for the game:

Match this promise with a type B promise. The function is applied as soon as the promise is paid.

Function:

 new Function<Double,Result>() { public Result apply(Double pi) { return ok("PI value computed: " + pi); } } 

converts a pi value of type Double to Result using the ok() function defined in Controller as soon as computePIAsynchronously .

but what is the logic of calling the apply method inside the function implementation?

This is the beauty of Promises and Scala . The Scala framework guarantees that the function will be applied when the promise is paid. If you want to read this topic, I suggest capturing the sources and documentation of scala.concurrent.ExecutionContext .

+2
source

Source: https://habr.com/ru/post/986834/


All Articles