Prefer to use an expression body for functions whose body consists of a single expression

Why you should care

Prefer using an expression body for functions with the body consisting of a single expression.

How we detect

CAST Highlight counts one occurrence each time a function consisting of a single instruction is using a body implementation (instructions enclosed between accolades).

 

fun foo(): Int {     // +1 VIOLATION
    return 1 
}
 
fun foo() = 1        // +0 good
 
fun foo(): Int {     // +0  because instruction is a "if" statement
   if (toto) {
       return 1
    }
}
 
fun foo(): Int {     // +0  because instruction is a "if" statement
   if (toto) {
       return 1
    }
}
 
// +0 because the instruction is written over at least 5 lines.
public inline fun <T, K> Iterable<T>.groupingBy(crossinline keySelector: (T) -> K): Grouping<T, K> {
    return object : Grouping<T, K> {
        override fun sourceIterator(): Iterator<T> = this@groupingBy.iterator()
        override fun keyOf1(element: T): K = keySelector(element1)
        override fun keyOf2(element: T): K = keySelector(element2)
    }
}

References

5362

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.