user3239558
user3239558

Reputation: 1827

Kotlin : can you explain member extension functions?

My code is as follows:

open class Particle

class Electron : Particle()

open class Element(val name: String) {

    open fun Particle.react(name: String): Unit {
        println("$name is reacting with a particle")
    }

    open fun Electron.react(name: String): Unit {
        println("$name is reacting with an electron")
    }

    fun react(particle: Particle): Unit {
        particle.react(name)
    }

}

fun main(args: Array<String>) {
    val selenium = Element("Selenium")
    selenium.react(Particle())
    selenium.react(Electron())
}

My output is as follows:

Selenium is reacting with a particle

Selenium is reacting with a particle

I don't understand : why the second output should not be "Selenium is reacting with an electron"?

If I added another subclass

class NobleGas(name: String) : Element(name) {

    fun react(particle: Electron): Unit {
        particle.react(name)
    }

}

fun main(args: Array<String>) {
    val neon = NobleGas("Selenium")
    neon.react(Particle())
    neon.react(Electron())
}

The output is : Selenium is reacting with a particle Selenium is reacting with an electron

Why the second output is "Selenium is reacting with an electron"?

Upvotes: 2

Views: 327

Answers (1)

zsmb13
zsmb13

Reputation: 89548

Extension functions compile to static function calls, and therefore which method to call is determined by the compile-time static types instead of the runtime types of the objects.

There isn't dynamic dispatch here like you get when you call a method that's overridden in a subclass and you get that implementation instead of what's in the base class. Basically, there's no overriding extension functions.

To the specific example: at compile time, inside the react(particle: Particle) function, the static type of particle is just Particle at compile time, so it will always call the extension function that's defined on the Particle class.

Upvotes: 2

Related Questions