Skip to content

New rule: Warn on ignored return value #2239

@bbaldino

Description

@bbaldino

The rule or changes you're looking for might have already been suggested!
Please search in the issues before creating a new one.

Expected Behavior of the rule

If a method which returns a value is called and the return value is ignored, detekt should issue a warning.

Example:

fun Byte.putBit(bitPos: Int, isSet: Boolean): Byte {
    return if (isSet) {
        (this.toInt() or (0b10000000 ushr bitPos)).toByte()
    } else {
        (this.toInt() and (0b10000000 ushr bitPos).inv()).toByte()
    }
}

It would be easy for someone to call myByte.putBit(1, true) and think it would be modified in place, but actually it returns the new value. A failure to handle this return value will almost certainly result in a bug.

Context

In many (most?) cases, the failure to observe a value returned by a function will result in a bug, but it can be an easy thing for a developer to forget. A warning will help catch instances where the return value should be handled. Cases which don't fall under this condition can suppress the warning (which also serves to explicitly document that it was intended).

I plan on taking a look at implementing this rule myself when I get a chance.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions