open classFeline funFeline.speak() = "<generic feline noise>" class Cat : Feline() fun Cat.speak() = "meow!!" fun printSpeak(feline: Feline){ println(feline.speak()) }
open class Caregiver(val name: String){ open fun Feline.react() = "PURRR!!!" fun Primate.react() = "*$name plays with ${this@Caregiver.name}*" fun takeCare(feline: Feline){ println("Feline reacts: ${feline.react()}") } fun takeCare(primate: Primate){ println("Primate reacts: ${primate.react()}") } }
1 2 3 4 5
val adam = Caregiver("Adam") val fulgencio = Cat() val koko = Primate("Koko") adam.takeCare(fulgencio) adam.takeCare(koko)
result:
1 2
PURRR!!! *Koko plays with Adam*
name conflict
扩展函数和成员函数同名是支持的。
默认执行的是成员函数,扩展函数是不会调用的。
但是当成员函数是私有的时,是调用的扩展函数(因为无法访问私有的成员函数)
1 2 3 4 5 6 7
class Worker { fun work() = "*working hard*" private fun rest() = "*resting*" } fun Worker.work() = "*not working so hard*" fun <T> Worker.work(t:T) = "*working on $t*" fun Worker.rest() = "*playing video games*"
1 2 3 4
val worker = Worker() println(worker.work()) println(worker.work("refactoring")) println(worker.rest())
result:
1 2 3
*working hard* *working on refactoring* *playing video games*