Assume that we have variable like var text: String?
.
When I want to cast it to non nullable type I can use:
text!!
text as String
Does they mean the same?
I know that these ways will throw an exception if text
is null
.
They are basically the same thing.
In Kotlin 1.3 (or older) first one will throw KotlinNullPointerExcption
for null
, and second one will throw TypeCastException
.
Kotlin 1.4 stops using its own exceptions and both expressions fail with regular NPE but as
version has a detailed message:
Exception in thread "main" java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With