PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 16, 2022

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

 December 16, 2022     java, java-8, syntax     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing