Potential Pitfall Extensions are Resolved Statically

suggest change

The extension method to be called is determined at compile-time based on the reference-type of the variable being accessed. It doesn’t matter what the variable’s type is at runtime, the same extension method will always be called.

open class Super

class Sub : Super()

fun Super.myExtension() = "Defined for Super"

fun Sub.myExtension() = "Defined for Sub"

fun callMyExtension(myVar: Super) {
    println(myVar.myExtension())
}

callMyExtension(Sub())

The above example will print "Defined for Super", because the declared type of the variable myVar is Super.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents