What's the different between Kotlin's `as? Type` vs `as Type?`

Viewed 476

Below is a code

        val firstAny: Any? = someVariable as? Any
        val secondAny: Any? = someVariable as Any?

To me, looks like both will produce the same result. Is there any difference between them i.e. as? Type vs as Type? ?

2 Answers

For Any? they are equivalent.

If you are casting to another type, then when the type cannot be cast:

  • someVariable as? Type will return null, but
  • someVariable as Type? will fail with ClassCastException.

Apparent one is safe-casting. The below won't crash, but return null when the type mismatch

val someVariable: Any? = 1
val someStr: String? = someVariable as? String // won't crash

The other is unsafe casting. It will crash when the type mismatch.

val someVariable: Any? = 1
val someStr: String? = someVariable as String? // will crash
Related