Method references with types [Re: lambda syntax tutorial]

Rémi Forax forax at univ-mlv.fr
Thu Aug 5 14:58:18 PDT 2010


Le 05/08/2010 23:32, Paul Benedict a écrit :
> My point is these two automatic conversions would be pretty cool. Just 
> to continue Brian's example:
>
> interface Extractor<T, U> {
>      public U get(T t);
> }
>
> class Arrays {
>      public <T, U extends Comparable<? super U>>
>      void sortBy(T[] array, Extractor<T, U> extractor) { ... }
> }
>
> // automatic SAM conversion
> Arrays.sortBy(strings, String#length());
>
> // automatic reflected method conversion
> java.lang.reflect.Method m = String#length();
>
> Paul

In fact, it will be something like

java.dyn.MethodHandle mh = String#length();

and to invoke it

int length;
try {
   length = mh.invokeGeneric("foo");
} catch(WrongTypeException e) {
    // it's a runtime exception so you can forget it but
    // it's just to remember that this call is not typesafe
    ...
} catch(Throwable t) {
    // you have also to deal with any exceptions
    // as previously said, this call is not typesafe
   ...
}

As you see the fact that you have to deal with exceptions
like any reflection calls make this syntax not really attractive
except if you are a developer of a dynamic language runtime
or want to play with invokedynamic.

It's better to create an interface like Brian does,
in that case you don't loose the type safety:

Extractor<String, Integer> extractor = String#length();
int length = extractor.get();

Also note that even if you use an Integer in the signature, the VM
is already able to not do the corresponding boxing
(see one of the last mail of Fredrik on this list).

Rémi

>
> On Thu, Aug 5, 2010 at 4:30 PM, Rémi Forax <forax at univ-mlv.fr 
> <mailto:forax at univ-mlv.fr>> wrote:
>
>     Le 05/08/2010 23:03, Paul Benedict a écrit :
>     > Good point Stephen. Parentheses should refer to methods, and
>     without them to
>     > fields. Your insight will definitely retain the separate
>     namespaces that
>     > Java has established.
>     >
>     > PS: Is Lambda also considering any support to turn method/field
>     references
>     > into java.lang.reflect types?
>     >
>
>     JSR 292 already adds support for instance field/static field
>     references
>     in the VM.
>     The question is just, should they have a syntax in Java.
>
>     Rémi
>
>



More information about the lambda-dev mailing list