Return to site

☕🎓JAVA CERTIFICATION QUESTION: Nested Lambdas

· java,ocp

and a class fragment:Given the following three functional interfaces:

 

and a class fragment:

 

What is the result? Choose one.

* MMBB is printed.

* WWWW is printed.

* WMWB is printed.

* MWBW is printed.

* Compilation fails in the main method because the code is ambiguous.

 

 

Answer: WMWB is printed.

Look at these lambdas in turn and notice which interface each might be compatible with.

The two lambdas that are nested inside the others are () -> "done" and () -> 1.

It is clear that the first of these is compatible with the interface Moo only.

The second lambda is compatible with Boo only.

Next, look at the outer lambdas: () -> { doIt(() -> "done"); } and () -> { doIt(() -> 1); }.

You know that the return type of the first enclosed lambda is String and that of the second is int.

However, notice that these enclosing lambdas are block lambdas, that is, they include curly braces and must, therefore, define entire method bodies.

However, the method bodies do not include return statements.

So, in both cases, the enclosing lambda will invoke the enclosed lambda and ignore the returned value.

The enclosing lambdas, therefore, have a void return type; as such, both are instances of the Woo interface.

At this point, you should have an instinct that since you have lambdas implementing all three interfaces, the output should contain all three letters: M, B, and W.

Let’s trace the execution to determine what actually happens.

Think about the order in which the enclosing and enclosed lambdas bodies actually execute.

In a Java method call, the arguments to a method invocation are always evaluated before the method is actually called.

However, the value of a lambda is an object that contains the method the lambda describes.

Java does not execute that method in constructing that object.

That means that when a lambda is passed as an argument, the method represented by the lambda has not been executed prior to the actual invocation of the method to which the lambda is being passed.

From this, you can tell that the very first lambda to be executed will be a Woo, which will print W.

That one then delegates to the String-producing Moo and prints M.

The process then repeats with a W from the second line’s enclosing lambda, followed by a B from the enclosed lambda that’s a Boo type.

That results in the output WMWB.