Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a `fun func()` without calling a `fun <T> T.func()` with the same name?

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()
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading