Return Value Ignored
ID |
kotlin.return_value_ignored |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
reliability |
Description
Reports call sites whose return value is discarded when the called function is
annotated with @CheckReturnValue (recognised across the common annotation
packages that publish it, including javax.annotation and
org.jetbrains.annotations). The annotation marks a function whose result
must be consumed; ignoring it usually means the call was meant to mutate
something but the API is immutable, or a developer forgot to use the return
value.
Rationale
@CheckReturnValue
fun produce(): Int = 42
fun caller() {
produce() // result thrown away — the computation has no effect
}
@CheckReturnValue is a deliberate contract: "do not call me for side
effects". When the rule fires it almost always points at a real bug, because
the only reason to call a side-effect-free function is to use its result.
Remediation
@CheckReturnValue
fun produce(): Int = 42
fun caller() {
val v = produce() // consume the result
println(produce()) // or pass it onwards
}
Either consume the return value (assign, return, pass as argument, or use it
in an expression) or — if the call truly should be fire-and-forget — remove
the @CheckReturnValue annotation from the function declaration.