Target type casting for method arguments , Lambda

vipin cp :

Consider the following two functional interfaces ( java.lang.Runnable and java.util.concurrent.Callable<V>):

public interface Runnable {
    void run();
}

public interface Callable<V> {
    V call();
}

Suppose that you have overloaded the method invoke as follows:

void invoke(Runnable r) {
    r.run();
}

<T> T invoke(Callable<T> c) {
    return c.call();
}

Consider below method invokation

String s = invoke(() -> "done");

This will call invoke(Callable) . but How? How compliler is able to determine the Type as callable? I didn't understand from Oracle doc i have read.

Naman :

Since () -> "done" returns a string value "done" which is what the call method of a Callable is responsible for in:

String s = invoke(() -> "done"); 
// from impl. of 'invoke', the variable 's' is assigned value "done"

On the other hand run is a void method, what matches the type Runnable there could be a void call such as:

invoke(() -> System.out.println("done"))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140027&siteId=1