Functional interface behavior and method references

What happens when a reference to a method that belongs to a variable is destroyed?

public class Hey{
    public double bar;

    public Hey(){
        bar = 2.0d;
    }

    public double square(double num){
        return Math.pow(num , bar);
    }
}

Function<Double, Double> square;
whatsGonnaHappen: {
    Hey hey = new Hey();
    square = hey::square;
}//is hey still kept around because its method is being referenced?

double ans = square.apply(23d);
+4
source share
2 answers

Scope is a compile-time concept that defines where names can be used in source code. From JLS

The scope of the declaration is the area of ​​the program within which the entity declared by the declaration can be assigned to use a simple name if it is visible (§6.4.1).

, hey whatsGonnaHappen , , , hey , ( , ).

, , hey::square (, hey), hey, apply.

+11

:

Hey hey = new Hey();
Function<Double, Double> square = new DoubleDoubleFunction(hey);

DoubleDoubleFunction :

class DoubleDoubleFunction implements Function<Double, Double> {
    private final Hey hey;

    public DoubleDoubleFunction(Hey hey) {
        this.hey = hey;
    }

    @Override
    public Double apply(Double num) {
        return hey.square(num);
    }
}

, square Hey.

, IntelliJ lambdas / / , , . .

+2

Source: https://habr.com/ru/post/1610648/


All Articles