How does the compiler know which class the lambda is implementing? - java

I see Thread() takes both Runnable and String for single argument constructors. How does the compiler know that a lambda is implementing a Runnable class and not a String class?
(new Thread( () -> {
System.out.println("Deleting stats...");
})).start();
Maybe it goes by the number of methods in the class/interface? But what if a class had multiple constructors that took single argument class that only had one method, for example:
Thread( Runnable r );
Thread( Comparable c );
Thread( ActionListener al );
What happens then when you try to implement a lambda then? How would the compiler know which class the lambda is implementing?

The Java compiler must choose a functional interface type for the type of a lambda expression. This is governed by the JLS, Section 15.27.3, which states:
A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.
The type String is not a functional interface type, but Runnable is. The lambda takes no arguments and returns no data, so it is congruent with Runnable.
More generally, the types of parameters in a lambda expression must match the types of parameters of the single abstract method of a functional interface type, and the return types must match also.
In your example, each of the 3 functional interface types is distinct, so at most one will match. If there are multiple functional interface types that could possible match, that would be ambiguous, only resolvable by casting the lambda expression to the intended functional interface type.

Lambda expressions are converted to an instance of a class implementing a functional interface. A "functional interface" means an interface with only 1 (non-default) method in it.
String isn't an interface - it's a class. So the compiler looks at the lambda expression and knows that if the code is to make sense then it should convert the lambda to instance of an implementation of Runnable, as it's the only possible thing that could work!

Related

Method reference notation vs "standard" Lambda notation

I was expecting these to be simple drop-in replacements for each other, but they're not. Clearly I'm not understanding the notation.
Can anyone explain why does that happen?
playButton.setOnAction(e -> track.play());
Here, compiler is happy with play() having a signature of
void play()
but here
playButton.setOnAction(track::play);
it requires
void play(Event e)
Here is a quote from the Java language specification:
A method reference expression (§15.13) is potentially compatible with
a functional interface type T if, where the arity of the function type
of T is n, there exists at least one potentially applicable method
when the method reference expression targets the function type with
arity n (§15.13.1), and one of the following is true:
The method reference expression has the form ReferenceType :: [TypeArguments] Identifier and at least one potentially applicable
method is either (i) static and supports arity n, or (ii) not static
and supports arity n-1.
The method reference expression has some other form and at least one potentially applicable method is not static.
...
The definition of potential applicability goes beyond a basic arity
check to also take into account the presence and "shape" of functional
interface target types.
Every method reference should conform to a function interface (which is an interface that declares a single abstract method, non-overriding methods from Object class). The compiler needs to verify whether the provided reference resolves to a single existing method that has required arity (number of parameters) and their types match the types of the method declared by the target functional interface.
Let's have a look at the prior Java 8 code (code-sample from JavaFX tutorial by created Oracle):
button2.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
label.setText("Accepted");
}
});
That is the "shape" that needs to be filled with a code describing an action. Method handle() of the EventHandler interface expects an event as an argument. Whether it would be used or not, that's up to you, the key point is that the abstract method of the target interface expects this argument to be provided.
By using a lambda expression e -> track.play() you're explicitly telling to ignore it.
And when you're passing a method reference track::play, which should be classified as a reference to an instance method of a particular object (see), the compiler will try to resolve it to a method play(Event) and you're getting a compilation error because it fails to find one.
In this case, reference track::play is not an equivalent of lambda e -> track.play(), but () -> track.play(), which doesn't conform to the target functional interface EventHandler.
In case if you wonder, how a method reference which can be applicable to a non-static method of arity n-1 mentioned in the specification (see case ii) can look like, here is an example:
BiPredicate<String, String> startsWith = String::startsWith; // the same as (str1, str2) -> str1.strarsWith(str2);
System.out.println(startsWith.test("abc", "a")); // => true
System.out.println(startsWith.test("fooBar", "a")); // => false
And you can construct a similar reference which conforms to EventHandler interface and applicable an instance method of arity n-1 using one of the parameterless methods of the Event type. It's not likely to be useful in practice, but it would be valid from the compiler perspective of view, so feel free to try it as an exercise.

forEach parameter does not match Consumer functional interface parameters but code still compiles, why?

I am studying for the OCP exam and I noticed a following snippet of code, where the parameter to the forEach method invoked on a DoubleStream must match that of the DoubleConsumer functional interface, however the lambda does not match the required types, why does it still compile?
DoubleStream.of(3.14159, 2.71828)
.forEach(c -> service.submit(
() -> System.out.println(10*c)
));
DoubleConsumer (accepts an argument of type Double and has a return type of void), however this forEach has a return type of Future<?> where ? denotes the return type of the Runnable lambda which is void, Future - this is not void. I am saying this because the return type of service.submit(...) is Future<?> it is not void, why does this code compile?
It is not really true that the return type of the lambda expression and the return type of the function type of the target functional interface type has to exactly match. The Java Language Specification specifies that void is a special case.
In §15.27.3, it says:
A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.
We are in an invocation context here. T is DoubleConsumer. The ground target type derived from it is also DoubleConsumer, and its function type is a method that takes a double and returns void.
Let's see what does "congruent" mean:
A lambda expression is congruent with a function type if all of the following are true:
[...]
If the lambda parameters are assumed to have the same types as the function type's parameter types, then:
If the function type's result is void, the lambda body is either a statement expression (§14.8) or a void-compatible block.
"assumed to have the same types as the function type's parameter types" basically means that you did not explicitly write out the type of c.
A statement expression is just an expression that can be made into a statement by adding a ; at the end. Any method call is a statement expression. This is why the submit call compiles.
5 is not a statement expression (but it is an expression), so c -> 5 does not compile.
If you think about it, by saying that methods that returns something should not be assigned to functional interfaces whose function type has a void return type, you are saying that "functions that take a A and gives out a B" are not a kind of "consumers of A". However, they clearly are "consumers of A"! They take in an A after all. Whether or not something is a consumer of A doesn't depend on what they produce.
Hence, Java is designed to allow this.

Why can't the var keyword in Java be assigned a lambda expression?

It is allowed to assign var in Java 10 with a string like:
var foo = "boo";
While it is not allowed to assign it with a lambda expression such as:
var predicateVar = apple -> apple.getColor().equals("red");
Why can't it infer a lambda or method reference type when it can infer the rest like String, ArrayList, user class, etc.?
This has nothing to do with var. It has to do with whether a lambda has a standalone type. The way var works is that it computes the standalone type of the initializer on the RHS, and infers that.
Since their introduction in Java 8, lambda expressions and method references have no standalone type -- they require a target type, which must be a functional interface.
If you try:
Object o = (String s) -> s.length();
you also get a type error, because the compiler has no idea what functional interface you intend to convert the lambda to.
Asking for inference with var just makes it harder, but since the easier question can't be answered, the harder one cannot either.
Note that you could provide a target type by other means (such as a cast) and then it would work:
var x = (Predicate<String>) s -> s.isEmpty();
because now the RHS has a standalone type. But you are better off providing the target type by giving x a manifest type.
From the Local-Variable Type Inference JEP:
The inference process, substantially, just gives the variable the type of its initializer expression. Some subtleties:
The initializer has no target type (because we haven't inferred it yet). Poly expressions that require such a type, like lambdas, method references, and array initializers, will trigger an error.
Because a lambda expression by itself does not have a type, it can not be inferred for var.
... Similarly, a default rule could be set.
Sure, you can come up with a way to work around this limitation. Why the developers made the decision not to do that is really up to speculation, unless someone who was part of the decision making can answer here. (Update: answered here.) If you're interested anyway, you could ask about it on one of the openjdk mailing lists: http://mail.openjdk.java.net/mailman/listinfo
If I were to guess, they probably didn't want to tie lambda inference in the context of var to a specific set of functional interface types, which would exclude any third party functional interface types. A better solution would be to infer a generic function type (i.e. (Apple) -> boolean) that can than be converted to a compatible functional interface type. But the JVM does not have such function types, and the decision to not implement them was already made during the project that created lambda expressions. Again if you're interested in concrete reasons, ask the devs.
To everyone who is saying this is impossible, undesired, or unwanted, I just want to point out that Scala can infer the lambda's type by specifying only the argument type:
val predicateVar = (apple: Apple) => apple.getColor().equals("red")
And in Haskell, because getColor would be a standalone function not attached to an object, and because it does full Hindley-Milner inference, you don't need to specify even the argument type:
predicateVar = \apple -> getColor apple == "red"
This is extraordinarily handy, because it's not the simple types that are annoying for programmers to explicitly specify, it's the more complex ones.
In other words, it's not a feature in Java 10. It's a limitation of their implementation and previous design choices.
As several people have already mentioned, what type should var infer and why should it?
The statement:
var predicateVar = apple -> apple.getColor().equals("red");
is ambiguous and there is no valid reason why the compiler should pick Function<Apple, Boolean> over Predicate<Apple> or vice versa assuming the apple identifier in the lambda represents an Apple isntance.
Another reason is that a lambda in its own doesn't have a speakable type hence there is no way for the compiler to infer it.
Also, "if this was possible" imagine the overhead as the compiler would have to go through all the functional interfaces and determine which functional interface is the most appropriate each time you assign a lambda to a var variable.
To answer this we have to go into details and understand what a lambda is and how it works.
First we should understand what a lambda is:
A lambda expression always implements a functional interface, so that when you have to supply a functional interface like Runnable, instead of having to create a whole new class that implements the interface, you can just use the lambda syntax to create a method that the functional interface requires. Keep in mind though that the lambda still has the type of the functional interface that it is implementing.
With that in mind, lets take this a step further:
This works great as in the case of Runnable, I can just create a new thread like this new Thread(()->{//put code to run here}); instead of creating a whole new object to implement the functional interface. This works since the compiler knows that Thread() takes an object of type Runnable, so it knows what type the lambda expression has to be.
However, in a case of assigning a lambda to a local variable, the compiler has no clue what functional interface this lambda is implementing so it can't infer what type var should be. Since maybe it's implementing a functional interface the user created or maybe it's the runnable interface, there is just no way to know.
This is why lambdas do not work with the var keyword.
Because that is a non-feature:
This treatment would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals, or any other kind of variable declaration.
http://openjdk.java.net/jeps/286
In a nutshell, the types of a var and lambda expression both need inference, but in opposite way. The type of a var is inferred by the initializer:
var a = new Apple();
The type of a lambda expression is set by the context. The type expected by the context is called the target type, and is usually inferred by the declaration e.g.
// Variable assignment
Function<Integer, Integer> l = (n) -> 2 * n;
// Method argument
List<Integer> map(List<Integer> list, Function<Integer, Integer> fn){
//...
}
map(List.of(1, 2, 3), (n) -> 2 * n);
// Method return
Function<Integer, Integer> foo(boolean flag){
//...
return (n) -> 2 * n;
}
So when a var and lambda expression are used together, the type of the former needs to be inferred by the latter while the type of the latter needs to be inferred by the former.
var a = (n) -> 2 * n;
The root of this dilemma is Java cannot decide the type of a lambda expression uniquely, which is further caused by Java's nominal instead of structural type system. That is, two types with identical structures but different names are not deemed as the same, e.g.
class A{
public int count;
int value(){
return count;
}
}
class B{
public int count;
int value(){
return count;
}
}
Function<Integer, Boolean>
Predicate<Integer>

Does lambda expression work as an implementation of abstract method of interface?

The lambda expression below:
new Thread(() ->
doSomething()
).start();
Does the lambda expression () -> doSomething() implement the public abstract void run();?
Would (param1, param2) -> {} work in the cases where an interface has only one method with two parameters?
What to do with interfaces with two abstract methods using lambda expressions?
Thanks for anyone who can help me.
Does the lambda expression () -> doSomething() implement the public abstract void run();?
Yes, the lambda is desugared into an anonymous type which implements Runnable with the code supplied using the lambda syntax.
Would (param1, param2) -> {} work in the cases where an interface has only one method with two parameters?
Yes, it is important that the lambda shape matches the shape of the interface method.
What to do with interfaces with two abstract methods using lambda expressions?
You can't use lambdas directly here, but a typical workaround is to define a concrete class implementing the interface, and its constructor taking two lambdas of the appropriate shape. The implementation methods in the class delegate to these lambda objects.
Your lambda expression behaves like an abstract class instance that implements Runnable, but it's not necessarily implemented as an abstract class instance.
Yes.
A lambda expression cannot be used where an interface with more than one abstract method is expected. A lambda expression can only be used where a functional interface is required, which means a single abstract method.

Why can't I assign lambda to Object?

I was trying to assign a lambda to Object type:
Object f = ()->{};
And it gives me error saying:
The target type of this expression must be a functional interface
Why is this happening, and how to do this?
It's not possible. As per the error message Object is not a functional interface, that is an interface with a single public method so you need to use a reference type that is, e.g.
Runnable r = () -> {};
This happens because there is no "lambda type" in the Java language.
When the compiler sees a lambda expression, it will try to convert it to an instance of the functional interface type you are trying to target. It's just syntax sugar.
The compiler can only convert lambda expressions to types that have a single abstract method declared. This is what it calls as "functional interface". And Object clearly does not fit this.
If you do this:
Runnable f = (/*args*/) -> {/*body*/};
Then Java will be able to convert the lambda expression to an instance of an anonymous class that extends Runnable. Essentially, it is the same thing as writing:
Runnable f = new Runnable() {
public void run(/*args*/) {
/*body*/
}
};
I've added the comments /*args*/ and /*body*/ just to make it more clear, but they aren't needed.
Java can infer that the lamba expression must be of Runnable type because of the type signature of f. But, there is no "lambda type" in Java world.
If you are trying to create a generic function that does nothing in Java, you can't. Java is 100% statically typed and object oriented.
There are some differences between anonymous inner classes and lambdas expressions, but you can look to them as they were just syntax sugar for instantiating objects of a type with a single abstract method.

Categories

Resources