i have a problem with the message “`Receiver param...
# getting-started
u
i have a problem with the message “`Receiver parameter is never used`” when using extension function. Why the receiver is not used?? the code is below…
Copy code
class HelloService : HelloContext {
    fun execute() {
        this.printName("apple")
    }
}


interface HelloContext

fun HelloContext.printName(name: String) {
    println("name = ${name}")
}
image.png
j
Because the code would run just as well if printName was its own function. There is no reference to this within the function
👍 2
u
oh the reason is
no this reference in the printName function
!! thank you jacob!
i have two more questions… @Jacob Using the extension functions that is not self referenced is bad practice?? I declared a HelloContext interface and extension functions of HelloContext will handle core domain logics. So not implement the HelloContext, they can’t use the extension functions… This is my intention. and how can i suppress the warning `Receiver parameter is never used`”?
v
Why do you want it to be an extension function of that receiver type if you don't use the receiver?
u
the reason is i want to limit the scope that the extension function can be called not Visibility Modifer if the function is private, i cannot test directly. But By the extension function that the receiver is not used, it cat test easily like using public visibility. (But other type cannot call this functions like using private modifier…) that’s what i want to do this!
t
I think what's going on is, that printName doesn't use
this
and therefor it can also just be a function in it's own file. It doesn't have to be an extension function of anything, it can be a function without a class that you can also import in other places 🙂
👍 1
v
Of course other types can call your extension function if it is visible to them. They just need an instance of
HelloContext
.
👍 1
j
As a general rule, you want to limit the amount of variables in scope for any line of logic. The warning is telling you that you have put HelloContext in your scope without a good apparent reason to do so.
u
I understand clearly. thank you!
🙌 1
143 Views