posted 1 month ago
Hmmm, I think Tim is sending you on a path to more confusion. The original code does, indeed compile (well, once you replace '˃' with '>' - those are not the same character). And the advice about "extracting" the lambda doesn't help unless you understand it well enough to know what the lambda means. The confusion comes because the compiler is filling in the gaps for several things that are not explicitly specified here.
Note that when "(var x, var y)" is used, it's used inside the check() method:
So the compiler, to interpret the lambda, will use what it knows about the declared types of the check() method:
The only way the compiler can interpret the check() call is if the first argument is a Climb instance. So the question is, can the compiler do that? This involves a lot of behind the scenes "magic" to make that work, in ways that are very carefully spelled out in the JLS, but a real pain to understand all the details. But basically, when the compiler sees a lambda, and it's in a place where the type is a functional interface, that is, an interface with just one abstract method, then the compiler will do whatever it can to interpret the lambda as an instance of that interface. In this case, the interface is Climb:
Well, that's a functional interface, with just one (non-static, non-default) method. So the compiler will do its best to interpret the lambda
as if it represents the missing method
That means that the two vars are interpreted as ints.
It also needs to return a boolean - which we don't see happening, explicitly. But here we can use another "magic" property of lambdas, that if they need to return something, and they end in a simple expression, they actually return that expression, without saying so. So
is equivalent here to
and now it's considered as an implementation of the isTooHigh() method:
In the elder days of Java (1.1), the closest equivalent of this would have been an anonymous class:
(If you haven't learned about anonymous classes yet, just ignore for now. They're much less important now than they used to be, though they're still legal and you do see them occasionally.)
But since Java 1.8, you can implement essentially the same thing much more concisely as
or even
(The var keyword wasn't adding anything useful there, anyway.)
As for this discussion of default values, I don't really know where that's coming from - I haven't tried to decode that branch of the conversation. There are no default values for local variables or method parameters, only for member fields (static or non-static). The only values that x and y ever have are the ones passed into it. In the code shown, that's a height of 5 for x, and a constant 10 for y. Defaults are not needed, which is good since they don't exist.