Function Returning Constant

ID

kotlin.function_returning_constant

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

readability, redundant

Description

Reports non-abstract function declarations whose entire body is a single return <literal> (block form) or whose expression body is a bare literal. Such functions always return the same constant — the call invokes a function just to read a value the caller could have referenced directly.

Rationale

// Bad
fun pi() = 3.14            // FLAW — use `const val PI = 3.14`
fun greeting() = "hello"   // FLAW

fun zero(): Int {
    return 0               // FLAW
}

// Good
const val PI = 3.14
const val GREETING = "hello"

fun nextId(): Int = counter++   // OK — varies per call
override fun toString() = "Foo" // OK — override is intentional

Constants exposed as functions add call-site overhead, prevent compile-time inlining, and obscure the fact that the value never changes. A const val top-level declaration communicates intent better, and inlining the literal at the use site is often clearer still.

Remediation

Replace the function with one of:

  • A top-level const val if the value is a compile-time constant.

  • A val initialiser when the value is computed once but not constant.

  • Inline the literal at the call site if the function only has one or two callers.

The rule already skips override, abstract, expect, and external functions — those bodies cannot be removed.