Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Is it possible to assign a method reference to a variable?

Tags:

java

I Googled for an answer to this question but couldn't find one.

In Java 8, I know this is possible:

// someMethod is defined as: someMethod(AFunctionalInterface i)
someMethod(someObject::someOtherMethod);

Question is: is it possible to do the following

AFunctionalInterface i = anObject::SomeMethod;

Also, is it possible to assign a lambda to a variable and pass it around, like so?

Printer f = () -> System.out.println(..); methodThatTakesPrinter(f);

like image 847
Aviv Cohn Avatar asked Dec 01 '25 07:12

Aviv Cohn


1 Answers

Yes, it is possible, according to an example cited in the JLS:

Task t = () -> System.out.println("hi");
Runnable r = t::invoke;

In addition, the following is stated:

A method reference expression is compatible in an assignment context [emphasis mine], 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.

like image 85
nanofarad Avatar answered Dec 04 '25 00:12

nanofarad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!