Constants
suggest changeKotlin has two ways to declare a value that never changes:
valis a read-only property or variable. It's assigned once, but the value can be computed at runtime and can be of any type.const valis a compile-time constant. The value must be known when the code is compiled, it must be a primitive type orString, and the compiler copies it into every place that uses it.
val |
const val |
|
|---|---|---|
| value known at | runtime | compile time |
| allowed types | any | Int, Long, Double, Boolean, Char, other primitives, unsigned types, String |
| allowed where | anywhere | top level, object, companion object |
| usable in annotations | no | yes |
| JVM bytecode | private field + getter | public static final field, value inlined at use sites |
Declaring const val
A const val can be declared at the top level of a file, inside an object declaration, or inside a companion object:
const val APP_NAME = "Inventory"
const val MAX_ITEMS = 100
const val TIMEOUT_MS = 30 * 1000L
const val GREETING = "Welcome to $APP_NAME"
const val NAME_LEN = APP_NAME.length
const val HEX = 0xFF
const val PI_ISH = 22.0 / 7
const val FLAG = MAX_ITEMS > 50 && NAME_LEN < 20
object Http {
const val OK = 200
const val NOT_FOUND = 404
}
class Server {
companion object {
const val DEFAULT_PORT = 8443
}
}
fun main() {
println("$APP_NAME $MAX_ITEMS $TIMEOUT_MS")
println(GREETING)
println("$NAME_LEN $HEX $PI_ISH $FLAG")
println("${Http.OK} ${Http.NOT_FOUND} ${Server.DEFAULT_PORT}")
}
Inventory 100 30000
Welcome to Inventory
9 255 3.142857142857143 true
200 404 8443
The initializer is a constant expression: literals, other const vals, arithmetic, comparison and logical operators, string templates made of constants, and a few intrinsics like String.length. The compiler evaluates it, so TIMEOUT_MS is stored as 30000, and GREETING as the finished string "Welcome to Inventory".
Constants are accessed like any other property: MAX_ITEMS from the same package (or after an import, see packages and imports), Http.OK through the object, and Server.DEFAULT_PORT through the class name.
What can't be const
The compiler tells you exactly why something can't be a constant:
import kotlin.time.Duration.Companion.seconds
const val STARTED = System.currentTimeMillis()
const val TIMEOUT = 30.seconds
const val SIZES = listOf(1, 2, 3)
const val NAME: String? = null
class Config {
const val VERSION = 3
}
fun main() {
const val LOCAL = 1
}
err.kt:3:21: error: const 'val' initializer must be a constant value.
err.kt:4:1: error: const 'val' has type 'Duration'. Only primitive types and 'String' are allowed.
err.kt:5:1: error: const 'val' has type 'List<Int>'. Only primitive types and 'String' are allowed.
err.kt:6:1: error: const 'val' has type 'String?'. Only primitive types and 'String' are allowed.
err.kt:9:5: error: const 'val' is only allowed on top level, in named objects, in companion objects or companion blocks.
err.kt:13:5: error: modifier 'const' is not applicable to 'local variable'.
The rules:
- no function calls, except the few the compiler can evaluate itself. Even
"abc".uppercase()is rejected. - only primitives, unsigned types (
const val MASK: UInt = 0xFFu) andString. NoDuration,BigDecimal, collections, arrays or your own classes. - no nullable types, so no
nullconstants - not in a regular class (each instance would get its own copy, which defeats the purpose), and not as a local variable
- no custom getter and no
var
For everything else use a plain val, described below.
Constants in annotations
Annotation arguments must be known at compile time, so they accept literals and const val, but not a regular val:
annotation class Retry(val times: Int, val reason: String)
const val DEFAULT_RETRIES = 3
val runtimeRetries = 3
@Retry(times = DEFAULT_RETRIES, reason = "network is flaky")
fun fetch() {}
@Retry(times = runtimeRetries, reason = "oops")
fun upload() {}
ann.kt:9:16: error: only 'const val' can be used in constant expressions.
This is the most common reason to need const: sharing a value between annotations, for example a table name in JPA's @Table(name = ...), a route in @GetMapping(...) or a warning name in @Suppress(...). See declaring an annotation for more about annotations.
Constants in when
when branches don't require constants, but named constants make them much easier to read than magic numbers:
object HttpStatus {
const val OK = 200
const val CREATED = 201
const val NOT_FOUND = 404
const val SERVER_ERROR = 500
}
fun describe(code: Int): String = when (code) {
HttpStatus.OK, HttpStatus.CREATED -> "success"
HttpStatus.NOT_FOUND -> "not found"
in HttpStatus.SERVER_ERROR..599 -> "server error"
else -> "unknown ($code)"
}
fun main() {
for (code in listOf(200, 201, 404, 503, 302)) {
println("$code: ${describe(code)}")
}
}
200: success
201: success
404: not found
503: server error
302: unknown (302)
Inlining and binary compatibility
The compiler doesn't generate a field read when you use a const val. It copies the value into the calling code. A plain val in an object is read through a getter at runtime.
Most of the time you don't need to care. It matters when the constant lives in a library and the code using it is compiled separately. Here is a library with one constant and one read-only property:
package lib
object Limits {
const val MAX_UPLOAD_MB = 10
val maxDownloadMb = 10
}
and an app that uses them:
import lib.Limits
fun main() {
println("upload limit: ${Limits.MAX_UPLOAD_MB} MB")
println("download limit: ${Limits.maxDownloadMb} MB")
}
Compile both and run:
upload limit: 10 MB
download limit: 10 MB
Now change both values in the library to 50, recompile only the library, and run the app again with the new library:
upload limit: 10 MB
download limit: 50 MB
The app still sees the old constant. Disassembling the app with javap -c shows why. The constant was folded into the string literal at compile time, while the val is read through getMaxDownloadMb():
0: ldc #8 // String upload limit: 10 MB
...
21: getstatic #37 // Field lib/Limits.INSTANCE:Llib/Limits;
24: invokevirtual #41 // Method lib/Limits.getMaxDownloadMb:()I
The practical rule: a public const val is part of your API and its value should never change. Use it for values that are fixed by definition (HTTP status codes, protocol magic numbers, unit conversions). For values that might change between versions (limits, default timeouts, feature settings), use a plain val. Java's static final constants work the same way.
Constant-like values with val
Many values you think of as constants can't be const: a compiled Regex, a Duration, a set of reserved words. Put them in an object (or at the top level) as a val. They are computed once, when the object is first used:
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
object Validation {
const val MAX_NAME_LENGTH = 40
val EMAIL_REGEX = Regex("""^[^@\s]+@[^@\s]+\.[a-z]{2,}$""")
val RESERVED_NAMES = setOf("admin", "root", "system")
val SESSION_TIMEOUT: Duration = 30.seconds
}
fun validate(name: String, email: String): List<String> = buildList {
if (name.length > Validation.MAX_NAME_LENGTH) add("name too long")
if (name.lowercase() in Validation.RESERVED_NAMES) add("name '$name' is reserved")
if (!Validation.EMAIL_REGEX.matches(email)) add("bad email '$email'")
}
fun main() {
println(validate("alice", "alice@example.com"))
println(validate("Admin", "admin@localhost"))
println("session timeout: ${Validation.SESSION_TIMEOUT}")
println(Validation.RESERVED_NAMES is MutableSet<*>)
}
[]
[name 'Admin' is reserved, bad email 'admin@localhost']
session timeout: 30s
true
Storing a Regex in a val like this is also a performance win over calling Regex(...) inside a function, which would recompile the pattern on every call.
The last line shows a catch: setOf returns a LinkedHashSet typed as a read-only Set, so code that casts it to MutableSet can change your "constant". val only makes the reference read-only. See immutability for ways to make the contents truly immutable.
If computing the value is expensive and it may never be needed, use val x by lazy { ... } (see lazy initialization).
A val with a getter is not a constant
A val with a custom getter runs the getter on every access, so it can return a different value each time:
import java.time.LocalTime
object Clock {
val startedAt: LocalTime = LocalTime.now()
val now: LocalTime get() = LocalTime.now()
}
fun main() {
val a = Clock.startedAt
val b = Clock.now
Thread.sleep(20)
println(Clock.startedAt == a)
println(Clock.now == b)
}
true
false
startedAt is computed once, when Clock is initialized. now is recomputed on every read. This is why const doesn't allow getters.
Initialization order
Properties of an object (and top-level properties in a file) are initialized from top to bottom. If one val uses another one declared below it, it can see an uninitialized value. The compiler catches direct references, but not ones through a function:
object Settings {
val greeting = makeGreeting()
val appName = "Inventory"
val banner = makeBanner()
const val VERSION = 3
private fun makeGreeting() = "Hello from $appName"
private fun makeBanner() = "Inventory v$VERSION"
}
fun main() {
println(Settings.greeting)
println(Settings.banner)
}
Hello from null
Inventory v3
appName was still null when greeting was computed, even though its type is a non-nullable String. VERSION works no matter where it's declared, because the compiler inlined 3 into makeBanner(). With plain vals, declare the values first and the values computed from them after.
Using Kotlin constants from Java
const val compiles to a public static final field, so Java sees a real constant. A plain val in an object or companion object becomes a private field with a getter, unless you annotate it with @JvmField:
@file:JvmName("AppConstants")
package demo
import java.time.Duration
const val APP_VERSION = "2.1.0"
class Config {
companion object {
const val MAX_RETRIES = 5
val timeout: Duration = Duration.ofSeconds(30)
@JvmField val retryDelay: Duration = Duration.ofMillis(250)
}
}
object Defaults {
const val PAGE_SIZE = 20
val locale = "en-US"
@JvmField val country = "US"
}
import demo.AppConstants;
import demo.Config;
import demo.Defaults;
public class Main {
public static void main(String[] args) {
System.out.println(AppConstants.APP_VERSION);
System.out.println(Config.MAX_RETRIES);
System.out.println(Config.Companion.getTimeout());
System.out.println(Config.retryDelay);
System.out.println(Defaults.PAGE_SIZE);
System.out.println(Defaults.INSTANCE.getLocale());
System.out.println(Defaults.country);
switch (args.length) {
case Config.MAX_RETRIES -> System.out.println("five args");
default -> System.out.println("other");
}
}
}
2.1.0
5
PT30S
PT0.25S
20
en-US
US
other
Things to notice:
- Top-level constants end up in a class named after the file (
ConfigKt).@file:JvmName("AppConstants")gives it a nicer name. const valin a companion object becomes a static field of the outer class:Config.MAX_RETRIES. Because it's a true Java constant, it can be used as acaselabel in aswitch.- A plain
valin a companion needs the clumsyConfig.Companion.getTimeout(). With@JvmFieldit's a static field:Config.retryDelay. - In an
object, a plainvalisDefaults.INSTANCE.getLocale(), and@JvmFieldmakes itDefaults.country.
javap confirms what the Kotlin compiler generated:
public final class demo.Config {
public static final demo.Config$Companion Companion;
public static final int MAX_RETRIES;
public static final java.time.Duration retryDelay;
...
}
public final class demo.Defaults {
public static final demo.Defaults INSTANCE;
public static final int PAGE_SIZE;
public static final java.lang.String country;
public final java.lang.String getLocale();
...
}
Where to put constants
- Private to one file:
private const valat the top of the file. This is the simplest option and doesn't add anything to your API. - Belonging to one class: a
companion objectin that class, e.g.Server.DEFAULT_PORT. Make itprivateif only the class uses it. - A group of related constants: an
object, e.g.HttpStatus.OK. The prefix tells the reader where the value comes from and keeps the package namespace clean. See singleton objects. - Used across a module: top-level
const valin a file such asConstants.kt. Don't make one giant file of unrelated constants; group them by feature instead.
By convention, const val and top-level or object vals holding deeply immutable data use SCREAMING_SNAKE_CASE. A val holding mutable or changing data uses camelCase. See coding conventions.
Constants vs enums
When a constant describes one of a fixed set of choices, an enum is usually better. Integer constants don't stop callers from passing any other integer:
const val PRIORITY_LOW = 0
const val PRIORITY_HIGH = 1
fun scheduleOld(task: String, priority: Int) = println("$task -> priority $priority")
enum class Priority(val weight: Int) { LOW(0), HIGH(1) }
fun schedule(task: String, priority: Priority) =
println("$task -> ${priority.name} (weight ${priority.weight})")
fun main() {
scheduleOld("backup", PRIORITY_HIGH)
scheduleOld("cleanup", 42) // compiles, but 42 is meaningless
schedule("backup", Priority.HIGH)
// schedule("cleanup", 42) // error: type mismatch
println(Priority.entries)
}
backup -> priority 1
cleanup -> priority 42
backup -> HIGH (weight 1)
[LOW, HIGH]
The enum version is type-safe, has a readable toString(), can be listed with entries, and gives you exhaustive when checks. Keep plain constants for values that really are just numbers or strings, such as limits, sizes and keys. See Enum.
Built-in constants
The standard library already defines constants for limits of numeric types and math values. Don't redefine them:
import kotlin.math.E
import kotlin.math.PI
fun main() {
println("Int: ${Int.MIN_VALUE} .. ${Int.MAX_VALUE}")
println("Long: ${Long.MAX_VALUE}")
println("Byte: ${Byte.MIN_VALUE} .. ${Byte.MAX_VALUE}")
println("UInt: ${UInt.MAX_VALUE}")
println("Double: ${Double.MAX_VALUE} ${Double.MIN_VALUE}")
println(" ${Double.POSITIVE_INFINITY} ${Double.NaN}")
println("Int.SIZE_BITS=${Int.SIZE_BITS} Long.SIZE_BYTES=${Long.SIZE_BYTES}")
println("PI=$PI E=$E")
}
Int: -2147483648 .. 2147483647
Long: 9223372036854775807
Byte: -128 .. 127
UInt: 4294967295
Double: 1.7976931348623157E308 4.9E-324
Infinity NaN
Int.SIZE_BITS=32 Long.SIZE_BYTES=8
PI=3.141592653589793 E=2.718281828459045
Note that Double.MIN_VALUE is the smallest positive Double, not the most negative one. For that use -Double.MAX_VALUE.
Summary
- Use
const valfor primitive andStringvalues known at compile time. It's allowed only at the top level, in anobjector in acompanion object. - Only
const valcan be used in annotation arguments. const valvalues are inlined into calling code. Never change the value of a public constant in a library; use a plainvalfor values that might change.- For constant-like values of other types (
Regex,Duration, collections) use avalin anobjector at the top level. Remember thatvalmakes the reference read-only, not the contents. - From Java,
const valis astatic finalfield. Use@JvmFieldto expose a plainvalas a field instead of a getter. - Prefer enums over groups of integer constants that represent a fixed set of choices.