Why this doesn\'t work? I get compiler error \"Cannot make static reference to the non static method print...\"
public class Chapter3 {
public void print
If you mismatch types of the function and the objects you are generating the function from, you will see the non static error. For example, this line of code will not compile because the function expects a Foo as the type it is acting on, but the function is for a Foobar:
Function func = Foobar::getBar;
It doesn't just deal with when its in a for loop or any other argument nor does it have to deal with "what is in scope". It's a type mismatch error that java mislabeled when using the new function objects. Compare this to what happens when you construct other generics:
List list = new ArrayList();
That line of code will fail to compile with the error "Incompatible Types". Even better is that this code will also fail with incompatible types instead despite also dealing with functional objects in nearly the exact same way:
public void test() {
Function test2 = Foo::getDouble;
//fails with Incompatible types
test3(test2);
}
public void test3(Function function) {
//who cares
}
My best suggestion is when you start having this error, pull out the function declaration to a new line and you should be able to see what the actual issue is. Why java chose "non-static method cannot be referenced from a static context" is beyond me.