Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "double exclamation" same as "as" in Kotlin?

Tags:

kotlin

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.

like image 552
Wojtek Avatar asked Feb 13 '18 21:02

Wojtek


1 Answers

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

like image 121
Miha_x64 Avatar answered Sep 28 '22 02:09

Miha_x64