Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: Warning needs a unchecked cast to conform to <InterfaceName>

Tags:

java

generics

I have an interface

interface x {
    A getValue();
}

and the implementation

class y implements x {
    public B getValue() { return new B();}
}

B is a subclass of A. This works because of covariant overriding, I guess.

But if I rewrite the interface as

interface x{
    <T extends A> T getValue();
}

I get a warning in the implementation that

Warning needs a unchecked cast to conform to A.getValue()

What is the difference between 2 versions of the interface? I was thinking they are the same.

like image 342
Surya Avatar asked Jul 24 '09 17:07

Surya


People also ask

How can I avoid unchecked cast warnings?

If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.

What are unchecked warnings in Java?

An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.

How do you stop unchecked cast Kotlin?

1 Answer. Show activity on this post. Adding @Suppress("UNCHECKED_CAST") (also possible through IDEA's Alt + Enter menu) to any of statement, function, class and file should help.


1 Answers

The second version of the interface is wrong. It says that the getValue will return any subclass you ask for - the return type will be inferred based on the expression on your left hand.

So, if you obtain a reference to an x (let's call it obj), you can legally make the following call without compiler warnings:

x obj = ...;
B b = obj.getValue();

Which is probably incorrect in your example, because if you add another class C that also extends A, you can also legally make the call:

C c = obj.getValue();

This is because T is not a type variable belonging to the interface, only to the method itself.

like image 156
waxwing Avatar answered Oct 06 '22 00:10

waxwing