简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM