Avoid using multiple labeled returns in lambda expression

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, avoid using multiple labeled returns in a lambda. Consider restructuring the lambda so that it will have a single exit point. If that’s not possible or not clear enough, consider converting the lambda into an anonymous function.

How we detect

CAST Highlight counts one occurrence each time a lambda is using several labeled returns.

fun foo1() {
listOf(1, 2, 3, 4, 5).forEach lit@{
if (it == 3) return@lit // first labeled return 
return @lit // second labeled return => VIOLATION



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.