Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 953
Sam Avatar asked Nov 12 '18 15:11

Sam


2 Answers

Think of it this way:

Doll d = null;

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

like image 158
Jacob G. Avatar answered Sep 28 '22 00:09

Jacob G.


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.

like image 33
Eran Avatar answered Sep 28 '22 01:09

Eran