daqpan
daqpan

Reputation: 3

<T extends Enum<T>> T[] as a return type in Java 8

I am looking at some code which compiles in java 7 but fails to compile in Java 8.

class Test {
    public <T extends Enum<T>> T[] doSomething(...) {...}

    public <T extends Enum<T>> T[] methodWhichCallsDoSomething() {
        ...
        return doSomething(...);
}

The error is as follows:

incompatible types: inference variable T has incompatible upper bounds java.lang.Enum<T>,T

I am running jdk 1.8.0_71.

Does anyone know a workaround or solution for getting this to compile and work in Java 8?

EDIT: The error message is given for the line calling doSomething(), for the col just before the parenthesis.

Upvotes: 0

Views: 487

Answers (1)

Holger
Holger

Reputation: 298233

The problem is caused by what you are passing to doSomething. You didn’t post the actual arguments, but from the signature we can deduce that, if at least one of doSomething’s parameters refers to T in any way, it is impossible for methodWhichCallsDoSomething to provide correct arguments (unless all are null), as no appropriate variable is in scope.

It’s very likely that the code compiled either, due to a compiler error or an unchecked operation, and in either case, it is indeed possible that this behavior has changed due to the new type inference rules.

A parameter-less method like methodWhichCallsDoSomething() promising to return whatever T[] the caller wishes, is broken anyway. There are several examples for similar anti-patterns, failing now under Java 8, like this and this. If such code happened to work in earlier version, it happened to work by accident and the problem occurring now were actually already there before.

For such broken code, getting a compiler error now, is the better of the possible symptoms as sometime, the code still compiles, but will suddenly break at runtime.

Upvotes: 3

Related Questions