Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested run blocks in Kotlin

Tags:

kotlin

I have a situation where I have nested run blocks. And I want to access outer run block this from inner run block. I tried this following IntelliJ hints but getting a ClassCastException on (this@run as String).equals(""). Is there a way to achieve this?

Sample code:

fun main(args: Array<String>) {
    "".run  {
        1.0.run {
            (this@run as String).equals("")
        }
    }
}
like image 422
Amardeep Avatar asked Jan 21 '26 10:01

Amardeep


2 Answers

Because there is more than one label with such a name run in that scope.

In order to access outer run block, just simply label it as anything that you want. For example, run1@ and run2@

fun main(args: Array<String>) {
    "".run run1@ {
        1.0.run run2@ {
            (this@run1 as String).equals("")
        }
    }
}

Btw, in Kotlin, equals("") is replaceable with == ""

like image 111
nhp Avatar answered Jan 23 '26 20:01

nhp


EDIT

You are getting java.lang.ClassCastException because this@run references value 1.0 (the closest one in the scope), which then you are trying to convert to String. If you want to use receiver instead of argument you can use the alternative apply function for one of yours lambdas

Example

fun main(args: Array<String>) {
    "".run  {
        1.0.apply {
            println(this@run == "")
        }
    }
}

Previous

Use also instead of run, this way you have the variable passed as a parameter of the lambda instead of a lambda with receiver.

Example

fun main(args: Array<String>) {
    "".also  { text ->
        1.0.run {
            println(this@run == "")
        }
    }
}

Alternatively, you could use apply instead of run

like image 29
Omar Mainegra Avatar answered Jan 23 '26 20:01

Omar Mainegra