我写了这段代码,但我不知道它为什么能编译。
UnaryOperator 接受一个特定类型的参数,并返回与其参数类型相同的结果。
我的问题:如果我放置一个返回null
的if 语句
,是否会出现编译错误?
null
不是其参数的类型(在我的例子中是 Doll)?
内置函数式接口(interface)(如 Consumer、UnaryOperator、Function)是否可以返回 null 而不是其标准返回值?
这是我的代码:
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));
}
}
非常感谢!
最佳答案
这样想:
Doll d = null;
null
是任何对象的有效引用,对于函数式接口(interface)也一样。
关于java - 具有不同类型返回的功能接口(interface)中的 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53264859/