Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoboxing and void

Notice how Integer.TYPE and Integer.class are both Class<Integer>, Double.TYPE and Double.class are both Class<Double>, and how you use autoboxing to convert between between int and Integer as well as double and Double. The question is whether this holds true for void: Void.TYPE and Void.class are both Class<Void>, but can you "convert" between void and Void?

To put it in another way, suppose you have this interface:

public interface Foo<T> {
    public T doSomething();
}

A class implementing Foo<Integer> is free to return an int in its implementation of doSomething() as the int will be boxed. Similarly for Foo<Double> returning double. So, for a Foo<Void>: since the only value of Void permissible is null (unless you do weird reflection, which is rarely justified), does this mean that you can omit the obligatory return null, effectively "boxing" the Void?

like image 804
Kelvin Chung Avatar asked Dec 20 '22 16:12

Kelvin Chung


1 Answers

does this mean that you can omit the obligatory return null, effectively "boxing" the Void?

Nope. This is easy to test for yourself, of course:

class Test {
    public Void foo() {
    }
}

Compilation gives:

Error: Test.java:3: missing return statement
    }

... or you could just read the JLS on autoboxing (section 5.1.7) which doesn't mention Void anywhere.

like image 98
Jon Skeet Avatar answered Dec 24 '22 01:12

Jon Skeet