lazycouu
01/11/2023, 10:38 AMHi, I discovered this while learning Kotlin grammar.
"return@map , return@filter"
ex1) val toInt = string
.map {
// it.toInt() // same?
return@map it.toInt()
ex2)
.map {
item ->
println(...)
// item.toInt() // same?
return@map item.toInt()
Is it the same function code?, Or is there something I don't know? I like this "return@xxx"
Can I have a problem with readability if I use it?
Luke Armitage
01/11/2023, 10:43 AMex2
you’ve simply given the lambda parameter a name. if you don’t do this, it defaults to it
, as in ex1
. unrelated to your return@map
, which is called a local return (iirc?) because you’re passing a lambda to a function (map
) whose functional argument (the lambda) is marked as inline
. see https://kotlinlang.org/docs/lambdas.html#returning-a-value-from-a-lambda-expressionJoffrey
01/11/2023, 10:46 AMCLOVIS
01/11/2023, 10:47 AMJoffrey
01/11/2023, 10:48 AMval toInt = string.map { it.toInt() }
For your second example, it's usually not advised to add side effects in transform lambdas like this. Also, when you have code inside the lambda's body that is so complex that a labeled return would help, I would argue the code would be cleaner if you extracted the body into a function with a good name.
In short, I have almost never seen a good case for using such returns to labels.lazycouu
01/11/2023, 10:49 AM