Chapter 15 Advanced classes

Under ‘Runtime hierarchy checks’
The example given states that if we have a reference to a supertype and then change it to a subtype, we are unable to call methods or use properties that are specific to the subtype, which makes a lot of sense. However, in practice, that does not seem to necessarily be the case:

The example below compiles (and runs) just fine on my computer

fun main() {
    open class SuperType(open val name: String) {
        fun someMethodAllSuperTypesHave() {}
    }
    class SubType(override val name: String) : SuperType(name) {
        val subtypeField = 10

        fun someMethodOnlySubtypesHave() {
            println(subtypeField)
        }
    }

    var generalType: SuperType = SuperType("George")
    generalType.someMethodAllSuperTypesHave()
    
    generalType = SubType("James")
    generalType.someMethodOnlySubtypesHave()
}

Hi @220284hk!

Thanks for the feedback! This is something we can certainly make clearer.

I believe your example is working because your variable is being “smart cast” to the subtype. Kotlin is pretty smart to figure this out!

That’s really confusing. I feel like the compiler is being too smart. Thanks for your answer :slight_smile: