What is lambda essentially?

Datetime:2016-08-23 00:35:30          Topic: Java8           Share

Android N is now released. One of the biggest feature for android developer is a custom compiler that can use the features of Java 8. Today I want to talk a little more about lambda.

I. samples of lambda in Java 8

Python, Ruby, Groovy also have lambda. So maybe a lot of people are familiar with the concept of lambda. Besides, there are a lot of introduction on lambda in java 8. So I will not descript too much concept of lambda. “Talk is cheap, show me the code”. Here is some samples:

1. Runable

before Java 8

new Thread( new Runnable(){
    @Override
    public void run(){
        System.out.println("run a thread");
    }
}).start();

Java 8

new Thread(()-> System.out.println("run a thread"))
    .start();

2. Click event

<= java 7

button.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v){
            System.out.println(v); // println the view you click
        }
    });

java 8

button.setOnClickListener( v -> System.out.println(v) );

Actually, there is a functional refrence in Java 8. So the codes can become better:

button.setOnClickListener(System.out::println)

System.out::println is an expression, which equals arg -> System.out.println(arg)

:: is a operator that tell the compiler this is a functional interface.

Then, what is functional interface? This question leads us to the next part.

3. lambda in other situations

Lambda is fit for java8’s stream API, RxJava perfectly. If you know these two libraries, you would know what I am talking about.

II. What is lambda essentially?

Lambda in Java represents a functional interface . Functional interface is an interface which has only one non-default method.

However, in fact , lambda is implemented by the anonymous nested class.

@FunctionalInterface
interface Print<T> {
    public void print(T x);
}

public class WhatsLambda {
    public static void PrintString(String s, Print<String> print) {
        print.print(s);
    }
    public static void main(String[] args) {
        PrintString("test", (x) -> System.out.println(x));
    }
}

When we run “javap -p WhatsLambda.class” in the build directory, we can find out a another function called “lambda$main$0(String str)”.

In fact, you can think of lambda in the way which the previous codes actually equals this:

@FunctionalInterface
interface Print<T> {
    public void print(T x);
}

public class WhatsLambda {
    public static void PrintString(String s, Print<String> print) {
        print.print(s);
    }

    final class $WhatsLambda$1 implements Print{
        @Override
        public void print(Object x){
            lambda$main$0(x);
        }
    }

    private static void lambda$main$0(String str){
        System.out.println(str);
    }

    public static void main(String[] args) {
        PrintString("test", new $WhatsLambda$1().print("test"));
    }
}




About List