Java compiler: How can two methods with the same name and different signatures match a method call?

后端 未结 2 1835
日久生厌
日久生厌 2020-12-16 19:27

I have this class called Container:

public class Container {

    private final Map map = new HashMap<>();

    publ         


        
2条回答
  •  感动是毒
    2020-12-16 19:53

    According to the JLS §15.12.2.2:

    An argument expression is considered pertinent to applicability for a potentially applicable method m unless it has one of the following forms:

    • An implicitly typed lambda expression1.
    • An inexact method reference expression2.
    • [...]

    Therefore:

    verify("bar", tokens.get("foo", e -> String.valueOf(e)));
    

    an implicitly typed lambda expression e -> String.valueOf(e) is skipped from the applicability check during overload resolution - both verify(...) methods become applicable - hence the ambiguity.

    In comparison, here are some examples that will work, because the types are specified explicitly:

    verify("bar", tokens.get("foo", (Function) e -> String.valueOf(e)));
    
    verify("bar", tokens.get("foo", (Function) String::valueOf));
    

    1 - An implicitly typed lambda expression is a lambda expression, where the types of all its formal parameters are inferred.
    2 - An inexact method reference - one with multiple overloads.

提交回复
热议问题