Skip to content

Instantly share code, notes, and snippets.

@hborders
Created September 27, 2018 21:23
Show Gist options
  • Save hborders/cd20ed743d75181e3427b398952fb401 to your computer and use it in GitHub Desktop.
Save hborders/cd20ed743d75181e3427b398952fb401 to your computer and use it in GitHub Desktop.
Some confusion over Kotlin extension methods
open class D {}
class D1: D() {}
fun D.foo() {
println("D.foo")
}
// this seems like an override, but isn't
// It's good that the compiler doesn't let
// me add `override`, but it's still not clear
// that this is independent from D.foo above
fun D1.foo() {
println("D1.foo")
}
open class C {
open fun D.foo() {
println("C.D.foo")
}
// this seems like an override, but isn't
// It's good that the compiler doesn't let
// me add `override`, but it's still not clear
// that this is independent from C.D.foo above
// or D1.foo above
open fun D1.foo() {
println("C.D1.foo")
}
fun callFooOnD(d: D) {
// not clear that this is "C.D.foo"
// rather than "D.foo"
d.foo()
}
fun callFooOnD1(d1: D1) {
d1.foo()
}
}
class C1: C() {
override fun D.foo() {
println("C1.D.foo")
}
override fun D1.foo() {
println("C1.D1.foo")
}
}
fun main(args: Array<String>) {
val d: D = D1()
val d1: D1 = D1()
println("top-level extensions")
d.foo() // prints D.foo
d1.foo() // prints D1.foo
println("instance member extensions")
C().callFooOnD(d)
// doesn't compile. This is good.
// C().callBarOnD1(d)
C().callFooOnD(d1)
C().callFooOnD1(d1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment