```Hi, I discovered this while learning Kotlin gra...
# getting-started
l
Copy code
Hi, 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?
l
in
ex2
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-expression
🙌 1
j
This feature is called Return to labels. Yes, those things are equivalent to what you put in the comment, but they are unnecessary clutter. I think people who prefer this are usually people who are used to Java's lambda expressions where returns are necessary to return a value from the lambda. In Kotlin, lambdas have many more useful facilities, and it's actually very common (and desirable) to use lambdas that consist of a single expression in their body. Adding labeled returns like this would make it way less readable in most cases.
🙌 1
c
The "unwritten rule" is: use labeled returns when there is an ambiguity, don't use them if there's none
1
🙌 3
j
Your first example is idiomatically written:
Copy code
val 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.
👍 1
🙌 1
l
Oh, I got you. All the answers were helpful to me.