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 same signature. Why does one work and the other doesn't?
Signature of String::toUpperCase
: String toUpperCase();
You have a method which
Takes a
String
and returns aString
. Such a method can have a number of patterns.A constructor
A function on
String
which takes no argumentsof a method which takes a String as the only argument
In every case, the method referenced has to take the String.
If not you can do this instead.
This tells the compiler to ignore the input.
There are 3 constructs to reference a method:
object::instanceMethod
Class::staticMethod
Class::instanceMethod
The line:
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:This Lambda expression works because Lambda gets
String
as parameter and returnsString
result - as required byCapitalizer
interface.The line:
Translates to:
Which does not work with the
Capitalizer
interface. You could verify this by changingCapitalizer
to:After this change
Main::toUpperCase
will compile.You should change:
to
You should read the java tutorial on method references. The different kind of method references and there is a similar example with
String::compareToIgnoreCase
(Reference to an Instance Method of an Arbitrary Object of a Particular Type).