Method references for non-empty arguments?

大城市里の小女人 提交于 2019-12-23 07:02:07

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15667804/method-references-for-non-empty-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!