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("")
}
}
}
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 == ""
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With