Kotlin explicit casting works on is or ! is an operator check variable and the compiler automatically casts the variable, but in explicit type casting, we used it as an operator.
1. Unsafe cast operator: as
2. Safe cast operator: as?
Unsafe cast operator: as
We use the cast operator to cast a variable to another type.
Output
The above example str1 variable is a string to convert type using as operator and converted value store in the str2 variable.
There might be a possibility of not casting value while executing code throws an exception unsafe casting.
Example 1:
Output
The above example str1 is Int but converted into the string so throw an exception.
Example 2:
We can not cast a nullable string to a non-nullable string.
Output
Safe cast operator: as?
Kotlin also provides facilities to safe cast operators as? If casting is not possible it returns null instead of throwing a Class castexception.
Output
Safe casting example
Happy Coding!