the full attempt in kotlin
# announcements
h
the full attempt in kotlin
d
Hi all, I have a few questions about kotlin. Why does kotlin not complain about unsafe casting from nullable? like
Copy code
var a: String? = null

    var b: String = a as String
it doesn’t warn that this kind of cast might not be safe
d
It's the same kind of cast as:
Copy code
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
hmm fair, for some reason I assumed that your code would complain about unchecked cast, but it doesn’t
s
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
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
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
(Technically it's the compiler that erases, not the JVM </nitpick>)
👍 1
👏 1
d
ok cool that makes sense
cheers