Smart castWe have seen in previous tutorial Kotlin Nullable Types and Non-Nullable Types how nullable type is declared. To use this nullable types we have an option to use smart casts. Smart cast is a feature in which Kotlin compiler tracks conditions inside if expression. If compiler founds a variable is not null of type nullable then the compiler will allow to access the variable. For example:When we try to access a nullable type of String without safe cast it will generate a compile error. To solve the above expression we use a safe cast as: Output: 6 While using is or !is for checking the variable, the compiler tracks this information and internally cast the variable to target type. This is done inside the scope if is or !is returns true. Use of is for smart castOutput: String length is 64 Use of !is for smart castOutput: String length is 64 Smart cast work according to the following conditions:
Next TopicKotlin Unsafe and Safe Cast Operator
|