Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

java - Can a lambda access members of its target functional interface?

I have created a simple interface using java8. In that it contains one method and one default method.

interface Lambda{

default void dummy(){
    System.out.println("Call this..");
}

void yummy();
}

I'm trying to us these two methods using the historical way like

public class DefaultCheck {

public static void main(String[] args) {

    DefaultCheck check = new DefaultCheck();
    check.activate(new Lambda() {

        @Override
        public void yummy() {
            dummy();
        }
    });

}

void activate(Lambda lambda){
    lambda.yummy();
}

}

Now i'm trying to implement the same thing using lambda expression, getting error like `dummy is undefined`

check.activate(() -> {
        dummy();
    });

Can any one please suggest, how to implement this scenario using Lambda expression ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It can't be done.

JLS 15.27.2 addresses this:

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

The transparency of this (both explicit and implicit) in the body of a lambda expression - that is, treating it the same as in the surrounding context - allows more flexibility for implementations, and prevents the meaning of unqualified names in the body from being dependent on overload resolution.

Practically speaking, it is unusual for a lambda expression to need to talk about itself (either to call itself recursively or to invoke its other methods), while it is more common to want to use names to refer to things in the enclosing class that would otherwise be shadowed (this, toString()). If it is necessary for a lambda expression to refer to itself (as if via this), a method reference or an anonymous inner class should be used instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...