Extension functions with conflicting names

What happens when an extension function has the same name as a member function?

The Worker class has a function work(): String and a private function rest(): String. We also have two extension functions with the same signature, work and rest:

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*"

Having extension functions with the same signature isn't a compilation error, but a warning: Extension is shadowed by a member: public final fun work(): String

It is legal to declare a function with the same signature as a member function, but the member function always takes precedence, therefore, the extension function is never invoked. This behavior changes when the member function is private, in this case, the extension function takes precedence.

It is also possible to overload an existing member function with an extension function:

val worker = Worker()

println(worker.work())

println(worker.work("refactoring"))

println(worker.rest())

On execution, work() invokes the member function and work(String) and rest() are extension functions:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.153.212