Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...