How does method reference casting work?

后端 未结 3 1727
走了就别回头了
走了就别回头了 2021-01-06 10:57
public class Main {
    interface Capitalizer {
        public String capitalize(String name);
    }

    public String toUpperCase() {
        return \"ALLCAPS\";
          


        
3条回答
  •  伪装坚强ぢ
    2021-01-06 11:48

    There are 3 constructs to reference a method:

    1. object::instanceMethod
    2. Class::staticMethod
    3. Class::instanceMethod

    The line:

    Capitalizer c = String::toUpperCase; //This works
    

    use 3'rd construct - Class::instanceMethod. In this case first parameter becomes the target of the method. This construct is equivalent (translates) to following Lambda:

    Capitalizer = (String x) -> x.toUpperCase();
    

    This Lambda expression works because Lambda gets String as parameter and returns String result - as required by Capitalizer interface.

    The line:

    c = Main::toUpperCase; //Compile error
    

    Translates to:

    (Main m) ->  m.toUpperCase();
    

    Which does not work with the Capitalizer interface. You could verify this by changing Capitalizer to:

    interface Capitalizer {
        public String capitalize(Main name);
    }
    

    After this change Main::toUpperCase will compile.

提交回复
热议问题