Why does this code return no output?
public class Test {
public static Runnable print() {
return () -> System.out.println("Hello world!!!");
}
public static void main(String[] args) {
Runnable r = Test ::print;
r.run();
}
}
This looks correct Runnable r = Test ::print(but Intellij adds warning that print method won't be called).
thanks in advance for explanation!
To be clear, IntelliJ is saying that "Result of 'Test.print()' is ignored", not that
printwon't be called.What is the "Result of
print"? Well,printreturns aRunnable- this:How did you ignore it? You assigned a method reference of
Test::printto aRunnable:Runnablerepresents a function that takes no arguments and returnsvoid(i.e. no return value). You are saying thatprint, which is declared to return aRunnableshould be assigned tor, which stores a function that returns nothing. That is clearly ignoring the return value ofprint.Note that you are not assigning the return value of
printtor, you are assigning the methodprintitself tor, not callingprintat all untilr.run().Assigning the return value of
printtorwould be written as:This is not "ignoring the result of
print", because you are assigning that result inr.Let's look at a less confusing example would be:
In the same way, you are saying that
getString, which is declared to return aStringshould be assigned tor, which stores a function that returns nothing. The fact thatprintreturns specifically aRunnableis not relevant tor. All that matters is,printreturns something, andrdoes not return a value, so you are ignoring the return value ofprint.