What is the type of a "method reference"?

Brian Goetz brian.goetz at oracle.com
Thu Jul 4 20:36:20 PDT 2013


(sorry for slow reply)

Method references, and lambda expressions, have no intrinsic type; their 
type depends on their context.  Their type will *always* be a functional 
interface, which is an interface with a single abstract method.

The compiler will enforce that the arity, argument types, return type, 
and exceptions are compatible (modulo allowable adaptations such as 
boxing, unboxing, or widening).

Here's an example where the "same" method ref could take on different types:

interface Predicate<T> {
     boolean test(T arg);
}

interface Function<T,U> {
     U apply(T arg);
}

Predicate<String> p = String::isEmpty;

Function<String, Boolean> f = String::isEmpty;

So, we see here that the method ref String::isEmpty (which refers to the 
nilary boolean-returning instance method) is compatible with either 
Predicate<String> or Function<String, Boolean> (the latter entails 
boxing.)

The type of a method reference depends on its context.  It could pick up 
type information from assignment context (as above), method invocation 
context, cast context, etc.

The following is illegal:

   Object o = String::isEmpty;

because we don't know what functional interface to convert 
String.isEmpty() to.  But the following is legal:

   Object o = (Predicate<String>) String::isEmpty;

Block<T> was renamed to Consumer<T>.





On 6/11/2013 5:50 PM, Behrooz Nobakht wrote:
> Hi,
>
> I have a question regarding the method references in Java 8. Let's say that
> I have a class:
>
> class MyClass {
>      Object doSomething(Object o);
> }
>
> And, I'm using the method reference MyClass::doSomething in a call
> such as SomeOtherClass.doAnotherThing(p,
> MyClass::doSomething). In this call, let's assume that p is an arbitrary
> parameter and doAnotherThing method knows how to provide the parameter for
> doSomething.
>
> My question is that how should the method doAnotherThing be declared?
>
> Studying the source code of Java 8, I found out that before Java 8 version
> b75, there was an abstraction java.util.function.Block which was removed
> from further revisions.
>
> So, maybe, another question is that since Block is not available what is
> its best replacement in the current version of Java 8? What is the
> top-level abstraction that represents a block of code such as a method
> reference? Or, in other words, if using lambdas, what is the type that
> could replace a lambda in method definitions?
>
> Having Block allowed to use define methods with parameters that are as
> general as a block of code (a method reference). Now, what should be used
> instead?
>
> I would appreciate your answers and explanations.
>
> Best,
> Behrooz
>


More information about the jdk8-dev mailing list