Friday, December 16, 2022

[FIXED] Why can I not assign a method reference directly to a variable of Object type?

Issue

Simple question about java-8 syntax. Why does JLS-8 restrict such expressions like:

Object of_ref = Stream::of;  // compile-time error

and allows only something like:

java.util.function.Function of_ref = Stream::of;
Object obj = of_ref; // compiles ok

?


Solution

That's because the target type of a method reference or a lambda expression should be a functional interface. Based on that only, runtime will create an instance of a class providing implementation of the given functional interface. Think of lambdas or method references as abstract concept. Assigning it to a functional interface type gives it a concrete meaning.

Moreover, a particular lambda or method reference, can have multiple functional interfaces as its target type. For example, consider the following lamda:

int x = 5;
FunctionalInterface func = (x) -> System.out.println(x);

This lambda is a Consumer of x. In addition to that, any interface with a single abstract method with following signature:

public abstract void xxx(int value);

can be used as target type. So, which interface would you want runtime to implement, if you assign the lambda to Object type? That is why you've to explicitly provide a functional interface as target type.

Now, once you got a functional interface reference holding an instance, you can assign it to any super reference (including Object)



Answered By - Rohit Jain
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.