Understanding as T? and as? T operator in Kotlin

--

Initially, I used to use as T? and as? T interchangeably thinking they have the same use case.

At first glance because of ‘?’ we think that both are the same and both are used to cast a variable to the nullable variables(T?) but the working of both operators are very different.

The as? T (or the safe cast operator) is used when we don't want our code to crash, in case the variable cannot be cast to type T.

In the case of as T? (or the unsafe cast operator), the app crashes if the variable cannot be cast to T?.

I have tried to show the differentiation of both the operators through the following images.

In case of as? , null is returned as we fail to cast to Int
In the case of ‘as’, an exception is thrown.
In this also, null is returned because of as? operator
In this case also because of ‘as’, an exception is thrown.

You can read more about the unchecked cast here — https://kotlinlang.org/docs/typecasts.html#unchecked-casts

--

--