Behavior of Functional Interface and Method Reference

时光怂恿深爱的人放手 提交于 2019-12-01 06:27:48

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

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).

The fact that the name hey is restricted to the body of the whatsGonnaHappen labeled statement doesn't have any bearing on whether the instance referenced by hey at runtime is a candidate for garbage collection (which I assume is what you're worried about).

Concerning the variable capture, yes, the method reference hey::square is a reference to an instance method of a particular object (the one referenced by hey) and will therefore capture the value of the variable hey when the method reference expression is evaluated to produce an instance and use it when apply is invoked.

Your method reference is essentially equivalent to doing this:

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

where the class DoubleDoubleFunction is defined like this

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);
    }
}

In other words, square holds a reference to the Hey.

I don't know about eclipse, but with IntelliJ you can easily translate method references and lambdas into anonymous / static nested / inner classes to see what's going on. I find this a very instructive thing to do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!