I
I
Igor-Novikov2020-04-20 14:08:23
Kotlin
Igor-Novikov, 2020-04-20 14:08:23

Why does a smart cast in Kotlin give access to another class?

There are 3 classes - A, B, C. Each of them has unique and overridden methods

open class A{
    open fun method(){
        println("Method from class - A")
    }

    open fun aMethod(){
        println("Unique method from class - A ")
    }
}

open class B :A(){
    override fun method() {
        println("Method from class - B")
    }

    open fun bMethod(){
        println("Unique method from class - B ")
    }
}

open class C : B(){
    override fun method(){
        println("Method from class - C")
    }

    open fun cMethod(){
        println("Unique method from class - C ")
    }
}


Why do I have access to a method of class B with the help of "smart casting" of a reference to class C to the type of class A?

val ref = C()
if(ref is A){
        ref.cMethod()
        ref.bMethod()
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-04-21
@Igor-Novikov

C is B and A too. smartcast has nothing to do with it - remove it, and everything will remain exactly the same. Because the parent's public methods are visible in the child's interface. Moreover, ref is A is always true, the IDE should tell you this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question