Let's say we got this class:
public class MyClass {
final int value = 0;
public int getValue() {
return value;
}
}
Is it somehow possible to take the output of the getValue()
method and increment it, or do any math with it, but by using the reference operator and not a lambda?
What I am looking to achieve is something like this, but with reference operators:
Function<MyClass, Integer> getVal = x -> x.getValue() 1;
If I write something like this, I will get an error:
Function<MyClass, Integer> getVal = MyClass::getValue 1;
CodePudding user response:
No, that's not possible.
A method reference is an expression, which has a value. The type of the value is computed at compile-time, depending on the context in which it is used (this is called a poly expression). A method reference is always an instance of a functional interface.
In your case, MyClass::getValue
returns some compatible interface, but the expression MyClass::getValue 1
causes the
operator to have to deal with that interface.
In JLS § 15.13.3, you can read about method references.
CodePudding user response:
I don't know that is the problem with lamba expressions here but you can always wrap your expressions and use references to those wrappers
stream.map(this::doIt)
public int doIt(MyClass x){
return x.getValue() 1;
}