Expression Body
ID |
kotlin.expression_body |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
conciseness, expression_body |
Description
Reports fun declarations whose block body contains exactly one statement — a
return <expression> — which can be rewritten as an expression body
(fun name(…) = expression).
Rationale
Kotlin offers expression bodies for functions whose entire purpose is to return
a value. The block-body form is required only when there is more than one
statement or when local side effects need explicit ordering. Using a block body
with a single return adds visual noise and obscures the fact that the function
is a pure expression. Expression bodies also let the compiler infer the return
type, keeping signatures concise.
// Bad — single return inside a block body
fun area(r: Int): Int {
return r * r
}
// Good — expression body
fun area(r: Int): Int = r * r