VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/kotlin-explicit-type-casting/

⇱ Kotlin Explicit Type Casting - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kotlin Explicit Type Casting

Last Updated : 12 Jul, 2025

Kotlin provides both smart casting and explicit type casting mechanisms to handle type conversions safely and effectively. In Smart Casting, we generally use is or !is an operator to check the type of variable, and the compiler automatically casts the variable to the target type, but in explicit type casting we use as operator. 
Explicit type casting can be done using :

  1. Unsafe cast operator: as
  2. Safe cast operator: as?

Unsafe cast operator : as

The as operator is used to explicitly cast a variable to a specified type. This is considered unsafe because if the cast is not valid, it throws a runtime exception.
In the below program, variable str1 of string typecast to target type using as operator. 

Example – Valid Unsafe Cast:

Output: 

It works fine

There might be possibility that we can not cast variable to target type and it throws an exception at runtime, that's why it is called as unsafe casting
When the Integer type is used to cast to the String type, then it throws ClassCastException

Example – Invalid Unsafe Cast:

Output: 

Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String


Casting Null to Non-Nullable Type

We can not cast a nullable string to non-nullable string, and it throws an exception TypeCastException.  

Output:

Exception in thread "main" kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String 

Hence, we have to use target type also as nullable String so that type casting throws no exception. 

Output: 

null


Safe cast operator: as?

Kotlin provides a safe cast operator as?, which attempts to cast a variable to the target type. If the cast is not possible, it simply returns null instead of throwing an exception. Here is an example, in which we are trying to cast Any type of string value that is initially known by the programmer into a nullable string then it works fine. When we initialize the Any with Integer value and try to cast into a nullable string then this typecasting is not possible and returns null to str3. 

Example – Safe Casts:

Output:

Safe casting
null
11

This approach is safer because it prevents runtime exceptions and allows null-check handling where necessary.

Comment
Article Tags:
Article Tags:

Explore