Search code examples
javaif-statementreturn-typeunary-operator

Null in functional interface with different type return


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!


Solution

  • Think of it this way:

    Doll d = null;
    

    null is a valid reference for any object, and isn't different for functional interfaces.