How does method reference casting work?

后端 未结 3 1725
走了就别回头了
走了就别回头了 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:34

    You have a method which

    public String capitalize(String name);
    

    Takes a String and returns a String. Such a method can have a number of patterns.

    A constructor

    c = String::new; // calls new String(String)
    // or
    c = s -> new String(s);
    

    A function on String which takes no arguments

    c = String::toLowerCase; // instance method String::toLowerCase()
    // or
    c = s -> s.toLowerCase();
    

    of a method which takes a String as the only argument

    // method which takes a String, but not a Main
    public static String toUpperCase(String str) { 
    
    c = Main::toUpperCase;
    // or
    c = s -> toUpperCase(s);
    

    In every case, the method referenced has to take the String.

    If not you can do this instead.

    c = s -> capitalize(); // assuming Main.capitalize() is static
    

    This tells the compiler to ignore the input.

提交回复
热议问题