May Be Const
ID |
kotlin.may_be_const |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
best-practice, efficiency |
Description
Reports val properties at file or object scope whose initialiser is a
compile-time literal (numeric, character, boolean, or a non-interpolated
string) and which therefore qualify to be declared const val.
Rationale
val PI = 3.14
val NAME = "kotlin"
object Constants {
val LIMIT = 10
}
A plain val with a literal initialiser still allocates a field, executes
its initialiser at first access, and cannot be referenced from places that
require a compile-time constant. The const modifier removes all of those
costs and unlocks several legitimate uses that the plain val cannot
support.
In particular, const val:
-
is inlined at the use site by the Kotlin compiler, so the field is gone from the generated bytecode entirely;
-
can be referenced from annotation arguments, which would otherwise require a string literal;
-
can be referenced from
whenbranches and other contexts that demand a constant expression; -
takes part in cross-module constant folding, so consumer modules see the literal value directly.
Remediation
const val PI = 3.14
const val NAME = "kotlin"
object Constants {
const val LIMIT = 10
}
Add the const modifier to any qualifying property. The candidates are
val declarations at file scope, inside a named object, or inside a
companion object whose initialiser is a compile-time literal and whose
type is a primitive or String. Instance properties of a class cannot be
const and are not reported.