【问题标题】:Null in functional interface with different type return具有不同类型返回的功能接口中的 Null
【发布时间】:2018-11-12 15:01:59
【问题描述】:

我写了这段代码,但我不知道它为什么会编译。

UnaryOperator 接受特定类型的参数并返回与其参数类型相同的结果。

我的问题:如果我将if-statement 与返回null 放在一起,是否存在编译器错误?

null 不是其参数的类型(在我的例子中是 Doll)?

内置函数式接口(如 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));
    }
}

非常感谢!

【问题讨论】:

    标签: java if-statement return-type unary-operator


    【解决方案1】:

    这样想:

    Doll d = null;
    

    null 是任何对象的有效引用,对于功能接口没有什么不同。

    【讨论】:

      【解决方案2】:

      内置函数式接口没有什么特别之处。任何返回引用类型的方法都可以返回null。这包括函数式接口方​​法的 lambda 表达式实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多