Boolean Return Null

ID

kotlin.boolean_return_null

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Code Smell

Language

Kotlin

Tags

CWE:476, boolean, null-safety

Description

Reports functions whose declared return type is Boolean? (nullable Boolean) and whose body contains at least one return null statement. Returning null from a Boolean? function introduces three-valued logic that callers must handle explicitly, which is almost always a design smell.

Rationale

A nullable Boolean creates three possible states: true, false, and null. Callers must use null-safety operators (?:, ?., !!) everywhere the return value is used. In most cases the null state represents a missing or unknown value that should be modelled more explicitly — for example with a sealed class, an enum, or a non-nullable Boolean combined with a separate boolean flag for the "unknown" state. Leaving the design as Boolean? with return null burdens every call site with additional null-handling ceremony.

// Bad — returns null as a third Boolean state
fun isActive(): Boolean? {
    if (!initialized) return null
    return active
}

// Good — return a sensible default
fun isActive(): Boolean = if (initialized) active else false

// Also good — sealed class for explicit tri-state
sealed class ActiveState {
    object Active : ActiveState()
    object Inactive : ActiveState()
    object Unknown : ActiveState()
}

Remediation

Replace return null with a concrete true or false default, or change the return type to a sealed class or enum that makes the "unknown" state explicit. If a nullable Boolean is genuinely needed, ensure callers always handle all three states clearly.