I am given a package that has two Kotlin functions named func: a regular fun func() and a generic extension fun <T> T.func(). They have different behaviour, and I’m trying to call fun func(). The problem is, the given scope in which I need to call fun func() has a receiver defined, so fun <T> T.func() is called instead. How do I omit the receiver parameter and avoid calling the extension function?
Kotlin Playground example: https://pl.kotl.in/rSieZpVuq
fun func() {
// I need this executed
println("Huge success!")
}
fun <T> T.func() {
// I don't need this executed
println("Complete failure!")
}
object GivenScope
fun main() {
GivenScope.run { // this: GivenScope
// I need it here
func()
}
}
>Solution :
Just call it with an explicit receiver. In your case, the method is defined on a companion object, so that’s your receiver.
GivenScope.run { // this: GivenScope
GivenLibrary.func()
}
If the function is a top-level function, you can call it with the package name as the receiver. There’s no package in your example code, but if the function is in, for instance, com.example.library, you could write
com.example.library.func()