samedi 1 août 2020

What is the advantage of lambda expressions over method variables?

I'm very new to lambda expressions, so please bear with me. Say I have an interface with a single abstract function:

public interface IAbsFunc {
    public abstract void absFunc(int x);
}

In this case, I can store a lambda expression in a variable:

public class Lambda {
    public static void main(String[] args) {
        IAbsFunc obj = (int x) -> System.out.println(x);
        obj.absFunc(3);
    }
}

If I'm understanding things right, this is like storing a method in a variable. However, this can already be done with java.lang.reflect:

public class Lambda {
    public static void main(String[] args) throws Exception {
        Method obj = PrintStream.class.getDeclaredMethod("println", int.class);
        obj.invoke(System.out, 3);
    }
}

Clearly I'm missing something here. In what situation would a lambda expression be preferable?





Aucun commentaire:

Enregistrer un commentaire