Skip to content
Advertisement

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;

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement