|
Kotlin supports different types of casts.
|
|
|
This is a normal cast using the as operator, which will throw an exception when x is not of the String type.
|
println("x has length ${xstr.length}")
fun withSafeCast(y: Any) {
|
|
This is a safe cast, using the as? operator. This will return null when y is not of the String type.
|
println("y has length ${ystr.length}")
fun withSmartCast(z: Any) {
|
|
Kotlin also has a feature called smart casts, which use the is operator.
|
|
|
Inside this if block, the compiler has determined that z has type String.
|
println("z is a string with length ${z.length}")
|
|
Smart casts also work when the is operator is negated.
|
println("z is not a string")
println("Yes, z is a string with length ${z.length}")
|