Hello, I've run into a situation and I've been try...
# announcements
o
Hello, I've run into a situation and I've been trying to figure it out. I have an extension function declared at the top level in my module, and I have an extension function declared within a class' scope. When I call a method that changes the receiver to this scope, I can't figure out how to access the top-level function. An example:
Copy code
fun MyObject.get(str: String): String {
        return get(str) {}
    }

class Scope {
        operator fun Any.get(str: String): Int = 1
}

// within method body
val myObject = MyObject()
val scope = Scope()

with(scope) {
  myObject.get("abc") // calls Scope's get()
}
How do I tell the compiler to call MyObject.get()? Suppose that both extension functions are define din libraries, so I can't easily change those names.
Testing here, if I'm in a method call I can forcibly change the receiver:
Copy code
with(scope) {
  with(this@methodClass) {
    myObject.get("abc") // calls MyObject.get()
  }
}
But it doesn't seem great, and won't work if I don't have a this.
c
you have endless recursion in
MyObject.get
I don't understand what you want to achieve there.
o
I want to call the first get(). The recursion was a mistake while I was simplifying my example, ignore it.
c
assuming
Copy code
fun MyObject.get(str: String): String {
	println("MyObject extension get: $str")
	return str
}
You can easily avoid the problem you describe:
Copy code
import com.example.MyObject
import com.example.Scope
import com.example.get as myGet

// within method body
val myObject = MyObject()
val scope = Scope()

with(scope) {
	myObject.myGet("abc") // prints "MyObject extension get: abc"
}
o
Ah, good, that answers it, thanks.
c
Sure, this is a very useful trick along with `typealias`es 🙂
o
Yeah, I had forgotten that you can alias imports