In the below code I am using a filter and a filter accepts a Predicate interface as parameter. We all know that Predicate has one method named test which accepts one parameter and returns a boolean.
I am of the understanding that the isEven() method that accepts no parameter is not a valid Predicate because unlike test() method it does not take any parameter, so how come my code is not showing a compile time error?
Also, would someone be kind enough to provide me a good source for understanding method reference, please.
The syntax that Piet showed is called "receiver parameter" and its only purpose is to allow the programmer to annotate the this keyword. It's very useful as a visual aid in explaining how method handles can be used though.
Yes, you can think of instance methods as having an implicit parameter for the object you're calling the method on. That's what happens under the hood anyway.
A parameterless instance method can either be used as a function that maps an instance of the declaring class to the return type of the method, or as a nullary function that just returns the return type of the method. In the latter case you'd use the method handle operator on an expression and not on a type name.
What Stephan means is that the compiler will interpret Data::isEven as the same as d -> d.isEven() And we know the latter is a valid λ for a Predicate::test() call. Using the class name in the method reference makes it look like a static method call, but it isn't static.
posted 6 days ago
So I believe due to the implicit "this" a call to is the same as
posted 6 days ago
shahid sarwar wrote:So I believe due to the implicit "this" a call to is the same as
No, it isn't. Both might give the same answer but semantically they are different.
The syntax of that method reference might look like a call to a static method, but it actually shorthand for calling an instance method. It is possible to write a static method whose method reference looks the same. The fact that two method references look the same does not imply that the two methods are the same. Only that they have the same name.
We don't have time for this. We've gotta save the moon! Or check this out: