Default label of a function parameter lambda (function name) is confusing

Background

When passing a lambda as a function parameter value, a return within the lambda requires a label. The default label is the name of the function.

Issue

The default label for a return in a lambda (the name of the function) is at least non-intuitive, if not confusing.

Example

fun main() {
  val str = generateRepeatedString(
      shouldIStop = { n ->
        // A bare return is forbidden here.
        // If you start with a bare return and get an error,
        // it is not apparent or intuitive that the label
        // should be the function name rather than the
        // parameter name.
        return@generateRepeatedString n == 3
      },
      whatToAppend = { n ->
        // In these oversimplified examples, the explicit
        // return isn't necessary.
        // Obviously, in the real world there may be
        // several/early returns.
        return@generateRepeatedString n.toString()
      }
  println("str=$str")
}

(more complete, runnable example in the Kotlin Playground)

The two return@generateRepeatedString return from the lambdas (shouldIStop and whatToAppend); it is not making the generateRepeatedString function return (as one might interpret by the label name).

Question / Suggestion

Can the default label take the parameter name instead of the name of the function? I think it would be clearer and more intuitive (like the workaround, below).

Workaround

We can manually make such returns clearer by specifying a label for the lambda like so (but it’s extra work and adds clutter):

fun main() {
  val str = generateRepeatedString(
      shouldIStop = shouldIStop@{ n ->
        return@shouldIStop n == 3
      },
      whatToAppend = whatToAppend@{ n ->
        return@whatToAppend n.toString()
      }
  )
  println("str=$str")
}
4 Likes