'Is it possible to use the reference operator in conjunction with other operators?
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;
Solution 1:[1]
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.
Solution 2:[2]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MC Emperor |
| Solution 2 | Antoniossss |
