How does reference casting work?

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

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

    public static void main(String[] args) {
        Capitalizer c = String::toUpperCase; //This works
        c = Main::toUpperCase; //Compile error
    }
}

Both are instance methods with the same signature. Why does one work and the other not?

Signature String::toUpperCase:String toUpperCase();

+4
source share
3 answers

There are 3 constructs to reference the method:

  • object::instanceMethod
  • Class::staticMethod
  • Class::instanceMethod

Line:

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

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

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

This Lambda expression works because Lambda takes Stringas a parameter and returns the result String- as required by the interfaceCapitalizer .

Line:

c = Main::toUpperCase; //Compile error

Translated to:

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

Capitalizer. , Capitalizer :

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

Main::toUpperCase.

+6

,

public String capitalize(String name);

a String a String. .

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

String,

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

,

// method which takes a String, but not a Main
public static String toUpperCase(String str) { 

c = Main::toUpperCase;
// or
c = s -> toUpperCase(s);

, , .

, .

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

.

+4

:

public String toUpperCase()

public static String toUpperCase(String text)

java . String::compareToIgnoreCase ( ).

An equivalent lambda expression to refer to the String :: compareToIgnoreCase method will have a formal parameter list (String a, String b), where a and b are arbitrary names used to better describe this example. The method reference will refer to the a.compareToIgnoreCase (b) method.

0
source

All Articles