Is there any way to get “From X” here / resolve th...
# getting-started
s
Is there any way to get “From X” here / resolve this ambiguity? Is the only way to reorder the scope / put the
with
closer to the function call?
Copy code
object X {
    fun Unit.print(): String = "From X"
}
object Y {
    fun Unit.print(): String = "From Y"
}

with(X) {
    with(Y) {
        Unit.print() // "From Y"
    }
}
m
when im testing this code, nothing happens. i used it in the official kotlin playground website.
s
Oh interesting - I am running it in the IntelliJ scratch file and it runs without issue
m
@Saharath Kleips mmm ... that line did not appear in the snippet 😕
Copy code
.also(::println)
Also, u did set an extennsion function inside singletons... with that in mind, the Y object will be used inside the inner
with() { ... }
s
Sorry in the snippet, I just commented the return value of the with 😅
Is there any way to say that I want the
Unit.print()
function from
X
rather than
Y
? Or is the only way to disambiguate to change the ordering?
m
k
Just change
Unit.print()
to
with(X) { Unit.print() }
. It doesn't matter that you already have an outer
with
.
s
Yeah it seems like that is the only option, thank you! I would just have code that’s something like:
Copy code
with(y) {
  with(x) { /** do something with x */ }
  // do stuff with y
  with(x) { /** do something with x */ }
  // etc.
}
So it would have been convenient to just start my function like
Copy code
fun doStuff() = with(x) {
  with(y) {
    ...
  }
}
k
You can still start your function the way you want it.
Copy code
fun doStuff() = with(x) {
  with(y) {
    //...do stuff with y...
    with(x) { /** do something with x */ }
  }
}
s
Yeah I was just trying to avoid writing out
with(x) { … }
every time I needed to disambiguate. Was hoping I could use a label or something
k
You can try using a local function:
Copy code
fun doStuff() = with(x) {
  fun printX() = Unit.print()
  with(y) {
    Unit.print()  // "From Y"
    printX()      // "From X"
  }
}
1
👍 1
s
That one is an interesting solution 👍