https://kotlinlang.org logo
Title
d

Dias

09/10/2018, 11:44 PM
Hi all, I have a few questions about kotlin. Why does kotlin not complain about unsafe casting from nullable? like
var a: String? = null

    var b: String = a as String
it doesn’t warn that this kind of cast might not be safe
d

diesieben07

09/10/2018, 11:46 PM
It's the same kind of cast as:
val a: Any = Any()
val b: String = a as String
It is a checked cast, so it is not unsafe. It can throw an exception, yes, but that is the nature of casts.
👆 1
d

Dias

09/10/2018, 11:47 PM
hmm fair, for some reason I assumed that your code would complain about unchecked cast, but it doesn’t
s

Shawn

09/10/2018, 11:48 PM
for reference, unchecked casts aren’t unsafe in the sense that they’re guaranteed to fail, they’re unsafe because the compiler has no way to guarantee type safety afterwards
d

diesieben07

09/10/2018, 11:48 PM
That is because the cast is not unchecked. The cast is checked at runtime. An unchecked cast on the other hand is not checked at runtime and you can end up with heap pollution. This happens due to generic erasure.
s

Shawn

09/10/2018, 11:48 PM
like you can “cast”
List<Int>
to
List<String>
technically, but it’s an unchecked cast since the JVM
javac
erases types at compile-time
d

diesieben07

09/10/2018, 11:49 PM
(Technically it's the compiler that erases, not the JVM </nitpick>)
👏 1
👍 1
d

Dias

09/10/2018, 11:50 PM
ok cool that makes sense
cheers