Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method references for non-empty arguments?

I was reading about the Java 8 features and I saw that they have method references, but I did not see how to specify which method when the method is overloaded. Does anyone know?

like image 539
Sled Avatar asked Mar 27 '13 19:03

Sled


2 Answers

Compiler will match the method signature with the functional interface.

Integer foo(){...}

Integer foo(Number x){...}

Supplier<Number>          f1 = this::foo;  // ()->Number, matching the 1st foo

Function<Integer, Number> f2 = this::foo;  // Int->Number, matching the 2nd foo

Essentially, f2 is something that can accept an Integer and return a Number, the compiler can find out that the 2nd foo() meets the requirement.

like image 198
ZhongYu Avatar answered Sep 19 '22 13:09

ZhongYu


From this Lambda FAQ:

Where can lambda expressions be used?

  • Method or constructor arguments, for which the target type is the type of the appropriate parameter. If the method or constructor is overloaded, the usual mechanisms of overload resolution are used before the lambda expression is matched to the target type. (After overload resolution, there may still be more than one matching method or constructor signature accepting different functional interfaces with identical functional descriptors. In this case, the lambda expression must be cast to the type of one of these functional interfaces);

  • Cast expressions, which provide the target type explicitly. For example:

Object o = () -> { System.out.println("hi"); };       // Illegal: could be Runnable or Callable (amongst others)
Object o = (Runnable) () -> { System.out.println("hi"); };    // Legal because disambiguated

So, you'll need to cast it if there are ambiguous signatures.

like image 22
Jean Waghetti Avatar answered Sep 21 '22 13:09

Jean Waghetti