Javatpoint Logo
Javatpoint Logo

Unsafe and Safe Cast Operator

Unsafe cast operator: as

Sometime it is not possible to cast variable and it throws an exception, this is called as unsafe cast. The unsafe cast is performed by the infix operator as.

A nullable string (String?) cannot be cast to non nullabe string (String), this throw an exception.

The above program throw an exception:

While try to cast integer value of Any type into string type lead to generate a ClassCastException.

Source and target variable need to nullable for casting to work:

Output:

String unsafe cast

Kotlin Safe cast operator: as?

Kotlin provides a safe cast operator as? for safely cast to a type. It returns a null if casting is not possible rather than throwing an ClassCastException exception.

Let's see an example, trying to cast Any type of string value which is initially known by programmer not by compiler into nullable string and nullable int. It cast the value if possible or return null instead of throwing exception even casting is not possible.

Output:

Kotlin
null





Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA