Mariano L :
I understand the error message. I know that I cannot access non-static methods in a static context. But why I can do the following:
Predicate<String> t = String::isEmpty; // this works
When isEmpty() is a non-static method for the class String? Look at the following example class. I understand the logic to not allow TestLamba::isEmptyTest; but what I don't understand is why String:isEmpty can break this rule:
import java.util.function.Predicate;
public class TestLamba {
public static void main(String... args) {
Predicate<String> t = String::isEmpty; // this works
Predicate<String> t2 = TestLamba::isEmptyTest; // this doesn't
}
public boolean isEmptyTest() {
return true;
}
}
This is the source for String.isEmpty. It's a pretty common method and you can see that it is not static:
public boolean isEmpty() {
return this.value.length == 0;
}
Khalid Shah :
isEmpty
is the function of String
Class and isEmptyTest
is the function of TestLamba
class.
import java.util.function.Predicate;
public class TestLamba {
public static void main(String... args) {
Predicate<String> t = String::isEmpty; // this works
Predicate<TestLamba > t2 = TestLamba::isEmptyTest; //Now this will work
}
public boolean isEmptyTest() {
return true;
}
}