If you are wondering how, in the previous section, we called functions that belong to supertypes from the base SuperHero type, and the compiler did not complain, the answer is the smart casting feature of the Kotlin compiler. Whenever you check in an if
or a when
statement that a type can be cast to another type, the compiler then allows you to access all members from the target type,that is,the compiler does the cast for you. Let's say we have a class hierarchy like the following one:
open class BaseUser(val name: String) open class User(name: String, val birthYear: Int) : BaseUser(name) { fun login() { } } open class AdminUser(name: String, birthYear: Int) : User(name, birthYear) { fun accessLogs() { } }
We have a function that accepts the base type; we can check with the is
keyword whether a type is an instance of another type. When the compiler knows that a type is actually an instance of a different type, you can immediately access all the members...