Shouldn't this show some unchecked cast warning?
# announcements
c
Shouldn't this show some unchecked cast warning?
a
Unchecked cast warnings are for generic casts (where it won't go wrong when casting but when accessing the type) (Badly worded but something like that)
r
Why do you think it should be an unchecked cast? B is a subtype of A so
a
could be a
B
and this check will be carried out at runtime
c
I mean a warning showing that this cast can have a
ClassCastException
because its not checked that
a
is B type, it can be A or C also
a
Every cast can have a ClassCastException If the compiler could guarantee the type then it wouldn't need the cast. So a cast is in theory always "dangerous"
1
c
Well you can check it before, like if(a is B){ a.sayHi()} right?
r
I don't know if there is an inspection you can activate in Intellij warning you about unsafe casts
I couldn't find one
a
Maybe its a rule in some linters I know in Java there's SonarLint that'll give you a warning when casting (without checking)
k
@carlos cdmp If you check it before then the compiler smartcasts and you don't need it either.
But the name "unchecked cast" specifically refers to a cast where even at runtime you can't be sure the cast is safe to do.
d
Yes, because when you cast to a generic type parameter, the code has to "assume" that the object is an instance of that type, because the type has been erased.