Safe casting
Recall that, in
Chapter 2
, Kotlin Basics, we introduced the as operator for casting a variable. If we want to safely cast to a type, or null if the cast would fail, then we can use the safe cast operator as?.
In the following example, we will cast a parameter that we know is a String, but the compiler doesn't know it is a String as we declared it as an Any:
val location: Any = "London"
val safeString: String? = location as? String
val safeInt: Int? = location as? Int