I have the following program that fails to compile:
Just block 1 compiles fine and works as expected - I can conditionally select an object and call a method on it inline.
Just block 2 also compiles fine and works as expected - I can conditionally assign a method reference to a Supplier<String>
variable and call .get()
on that variable.
However block 3 fails to compile:
Lambda.java:31: error: method reference not expected here
String res = ((Supplier<String>) (args.length > 0 ? Lambda::foo : Lambda::bar)).get();
^
Lambda.java:31: error: method reference not expected here
String res = ((Supplier<String>) (args.length > 0 ? Lambda::foo : Lambda::bar)).get();
I would think combining the ideas in block 1 and 2 I would be able to perform block 3 as the type of ((Supplier<String>) (args.length > 0 ? Lambda::foo : Lambda::bar))
is Supplier<String>
.
import java.util.function.Supplier;
class Lambda {
private final String s;
private Lambda(String s) {
this.s = s;
}
private static String foo() {
return "foo";
}
private static String bar() {
return "bar";
}
private String str() {
return s;
}
public static void main(String... args) {
// Block 1
Lambda l1 = new Lambda("x");
Lambda l2 = new Lambda("y");
System.out.println((args.length > 0 ? l1 : l2).str());
// Block 2
Supplier<String> s = (args.length > 0 ? Lambda::foo : Lambda::bar);
System.out.println(s.get());
// Block 3
String res = ((Supplier<String>) (args.length > 0 ? Lambda::foo : Lambda::bar)).get();
System.out.println(res);
}
}
To be clear: I'm not looking for a workaround here, this wouldn't be good quality code in the first place. I'm just curious why the last block fails to compile.