Are there ways to restrict the scope of a particul...
# announcements
s
Are there ways to restrict the scope of a particular extension function to where
this
is not the receiver? For instance, if I’m wrapping an existing API in a DSL, a
fun String.bar()
might behave differently depending on what
this
is. I’m not able to subclass the wrapped API data type as it’s final, and inline classes don’t provide delegates apparently. I thought this would work:
Copy code
class Foo {
  fun doSomething(it: String) {
    // TODO
  }
}

inline class Bar(val foo: Foo) {
  fun String.doSomething() = doSomething(this)
}
But
Bar(Foo()).doSomething("hello")
is undefined.
Seems like sort of “ad-hoc” polymorphism is still sort of an area of discussion: https://discuss.kotlinlang.org/t/extension-types-for-kotlin/1390
e
Does this work?
Copy code
fun Bar.barAction() {
    val string = "something"
    string.doSomething()
}
String.doSomething() is only valid within the scope of a Bar function
s
@Big Chungus Yeah I should have specified it is desirable in this case that the outer, non-receiver scope also be referenceable with this. Basically I need a polymorphic receiver like you’d normally get by nesting two apply or with functions.