2

The Kotlin documentation describes how to access this expressions in nested classes.

Is it possible to access this expressions in nested unnamed functions? e.g:

str = "abcde"
str.run {                                                                                                                                                                                              
this.substring(0..2).run {                                                                                                                                                                         
    println("${this} is a substring of ${???}")                                                                                                                                                    
}

1 Answer 1

4

Just for the sake of answering the question as asked, for situations where this can improve readability, you can use a label:

str.run outer@ { // Define a label
    this.substring(0..2).run {
        println("${this} is a substring of ${this@outer}") // Use the label
    }
}

Oftentimes, you'll have implicit labels to use. For example, if the outer call is changed to use a different function name from the inner call, you can access it:

with (str) {
    this.substring(0..2).run {
        println("${this} is a substring of ${this@with}") // Use the implicit label
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.