https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

smit01

02/09/2022, 6:31 AM
class A(val value:Int = 0) fun test(){ with(A(9)){ with(A(8)){ println(this.value) //output 8 println(this@with.value) //output 8 // My question is how to access A's object with value 9 } } }
e

ephemient

02/09/2022, 6:40 AM
use triple backticks ``` to start a code block in slack, it is much more readable. and if it's more than a few lines, use Slack's text snippet feature. see https://kotlinlang.org/community/slackccugl.html
👍 2
but the answer is: you can't, not without some changes
for example, you could give the lambdas an explicit label, so it's different than the default
Copy code
with(A(9)) outer@{
    with(A(8)) inner@{
        this@outer // A(9)
        this@inner // A(8)
👍 3
j

Joffrey

02/09/2022, 1:50 PM
While @ephemient perfectly answered your question, I would like to add that you should simply not do that in general. If you have to resort to labeled lambdas and labeled
this
or
return
, it is usually a smell that something could be extracted into a function. I'm usually (personally) a bit extreme about extraction into functions, but I would argue that if you reach a point where even the compiler needs help disambiguating names, it's probably a mess to read for humans. So this is definitely a line that I think should not be crossed (unless a particular use case calls for it in a very short function, there are always exceptions).
👍 1
s

smit01

02/09/2022, 5:37 PM
Understood very well thanks 🤗
2 Views