To cast a reference to a type explicitly, we use the as operator.
This operation will throw a ClassCastException if the cast cannot be performed legally:
fun length(any: Any): Int { val string = any as String return string.length }
Here, the null value cannot be cast to a type that is not defined as nullable.
It would have thrown an exception if the value was null.
To cast to a value that can be null, declare the required type as nullable:
val string: String? = any as String
To avoid the exception, use the safe cast operator as? .
This operator will return the casted value if the target type is compatible, otherwise it will return null.
In the next example, string would be a successful cast, but file would be null:
fun main(args: Array<String>) { val any = "java2s.com" val string: String? = any as? String val file: File? = any as? File //from w ww .j a v a 2s . co m println(file) }