Sam
Sam

Reputation: 566

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!

Upvotes: 5

Views: 1995

Answers (2)

Jacob G.
Jacob G.

Reputation: 29680

Think of it this way:

Doll d = null;

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

Upvotes: 5

Eran
Eran

Reputation: 393811

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.

Upvotes: 4

Related Questions