ArtB ArtB - 1 year ago 122
Java Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download