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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With