I write this code, but I don't know why it compiles.
The UnaryOperator takes a specific type argument and returns the result with the same type of its argument.
My question: if I put an if-statement
with the return null
, isn't there a compiler error?
null
isn't the type of the its argument (in my case is Doll)?
Can a built-in functional interface (like Consumer, UnaryOperator, Function) return null instead of its standard return?
This is my code:
import java.util.function.*;
public class Doll {
private int layer;
public Doll(int layer) {
super();
this.layer = layer;
}
public static void open(UnaryOperator<Doll> task, Doll doll) {
while ((doll = task.apply(doll)) != null) {
System.out.println("X");
}
}
public static void main(String[] args) {
open(s -> {
if (s.layer <= 0)
return null;
else
return new Doll(s.layer--);
}, new Doll(5));
}
}
Thanks a lot!
Think of it this way:
Doll d = null;
null
is a valid reference for any object, and isn't different for functional interfaces.
There's nothing special about built-in functional interfaces. Any method that returns a reference type can return null
. This includes the lambda expression implementation of the method of a functional interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With