Why you should care
The return keyword is relative to the nearest enclosing function (or anonymous function). So for returning from lambda, a labeled return is needed. But as recommended by official Kotlin coding convention, do not use a labeled return for the last statement in a lambda. Prefer lambda mechanism based on implicit return of the last expression used. If you need explicit return, then for a lambda you would have to use a heavy labeled return syntax. So in this case, prefer converting the lambda into anonymous function that use a simple return syntax.
How we detect
CAST Highlight counts one occurrence each time a labeled return is the last instruction of a lambda.
fun foo1() { listOf(1, 2, 3, 4, 5).forEach lit@{ if (it == 3) return@lit print(it) return @lit // terminal labeled return => +1 VIOLATION } }
References
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.