Use const val at the top level of a file: const val MAX_RETRIES = 3. It is a compile-time constant, Kotlin's answer to Java's static final, and it takes numbers, Char, Boolean and String. To group constants under a name, put them in an object or in a class's companion object. For a List or a value a function computes, use a plain val. Name constants in UPPER_SNAKE_CASE.
Kotlin has no static keyword, so the Java recipe public static final int MAX = 3; inside a class has no direct copy. Instead you have const val, a value the compiler knows and copies into every place that uses it, and three places to put it: the top level of a file, an object, or a companion object. The sections below cover all three, the types const allows and the compile errors for the rest, the difference between const val and val, enums for related values, and what Java code sees, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1const val at the top levelRecommended
A const val declared outside any class is the simplest constant: no wrapper, no import within the same package, and any file of the package can read it. A constant can be built from other constants with arithmetic, string concatenation and string templates, so TIMEOUT_MILLIS below is still a compile-time value. Mark a constant private to keep it inside its file; that is the usual home of a log TAG. Kotlin's coding conventions name constants in screaming snake case, MAX_ITEMS, as Java does.
// Top-level constants: no class needed const val APP_NAME = "Inventory" const val MAX_ITEMS = 500 const val PRICE_LIMIT = 9_999.99 const val DEBUG = false // Built from other constants, still known at compile time const val TIMEOUT_SECONDS = 30 const val TIMEOUT_MILLIS = TIMEOUT_SECONDS * 1000L const val USER_AGENT = "$APP_NAME/2.1" // private: visible only inside this file private const val TAG = "Main" fun log(message: String) = println("[$TAG] $message") fun main() { log("starting $APP_NAME") println("max items: $MAX_ITEMS") println("timeout: $TIMEOUT_MILLIS ms") println("user agent: $USER_AGENT") println("debug: $DEBUG, price limit: $PRICE_LIMIT") }
Output
The log line prints [Main] starting Inventory, and the derived values come out as timeout: 30000 ms and user agent: Inventory/2.1. TIMEOUT_MILLIS is a Long because of the 1000L. The type of each constant is inferred from its value, as for any val; write it out (const val MAX_ITEMS: Int = 500) when you want it on the page. Java code in the same project reads these through the file's class: MainKt.MAX_ITEMS for a file named Main.kt.
2Constants in an object or a companion object
To group constants under a name, declare them in an object and read them as Api.VERSION. To tie a constant to one class, the way a Java static final field belongs to its class, put it in that class's companion object: code inside the class uses the bare name, code outside writes OrderService.MAX_LINES. const val is allowed only in these places and at the top level, not in a plain class body. So where does a TAG go? Top level or companion both work. A private const val TAG at the top level is shorter and fine with one class per file; a companion keeps the tag with its class when a file holds several.
// object: constants grouped under a name object Api { const val BASE_URL = "https://api.example.com" const val VERSION = 3 const val USERS = "$BASE_URL/v$VERSION/users" } class OrderService { // companion object: constants that belong to this class companion object { private const val TAG = "OrderService" const val MAX_LINES = 50 } fun place(lines: Int): String = if (lines <= MAX_LINES) "[$TAG] placed $lines lines" else "[$TAG] too many lines: $lines" } fun main() { println(Api.USERS) println("API version ${Api.VERSION}") // Outside the class, name the class (not the companion) println(OrderService.MAX_LINES) val service = OrderService() println(service.place(3)) println(service.place(80)) }
Output
Api.USERS is assembled from the two constants above it and prints https://api.example.com/v3/users. From main, the companion constant reads as OrderService.MAX_LINES and prints 50; inside the class, TAG and MAX_LINES need no prefix, so the two calls print [OrderService] placed 3 lines and [OrderService] too many lines: 80. The TAG is private, so OrderService.TAG would not compile outside the class. A tag written as javaClass.simpleName follows renames, but it is a call made at run time, so it can only be a plain val.
3Which types const allows, and the compile errors
A const val must hold a value the compiler can work out on its own: Int, Long, Short, Byte, Double, Float, Char, Boolean, String, or an unsigned type such as UInt, written as a literal or built from other constants. A List, a data class, an Array, or the result of a function such as System.currentTimeMillis() or uppercase() is out, because it only exists once the program runs. The program below tries two of them and never runs.
// Fine: primitive types and String const val RETRIES = 3 const val GREETING = "Hello" // Not fine: a List, and a value known only when the program runs const val PORTS = listOf(80, 443) const val STARTED_AT = System.currentTimeMillis() fun main() { println("$GREETING $RETRIES $PORTS $STARTED_AT") }
Output
The compiler reports both lines. For PORTS it says Const 'val' has type 'List<Int>'. Only primitive types and 'String' are allowed. For STARTED_AT it says Const 'val' initializer must be a constant value. The fix for both is to drop const: val PORTS = listOf(80, 443) is still read-only and still named in capitals. Two related errors: const var gives Modifier 'const' is not applicable to 'vars'., and a const val in a plain class body is rejected because const is only allowed on top level, in named objects and in companion objects.
4const val vs val: compile time and run time
Both are read-only. The difference is when the value exists. The compiler copies a const val into every place that reads it, so reading Config.MAX_RETRIES is the same as writing 3 there. A plain val is computed at run time, the first time its object or file is used, and stored in a field behind a getter. Two things follow: only a const val can be an annotation argument (a plain val there fails with Only 'const val' can be used in constant expressions.), and reading a const val doesn't load the object that declares it.
object Config {
init {
println(" (Config object initialized)")
}
// const val: the compiler copies 3 into every place that reads it
const val MAX_RETRIES = 3
// val: computed once, when Config is first used at run time
val DEFAULT_TAGS = listOf("kotlin", "jvm")
val SLUG = "Define Constants".lowercase().replace(' ', '-')
}
// Annotation arguments must be compile-time constants
annotation class Retry(val times: Int)
@Retry(Config.MAX_RETRIES)
class Client
fun main() {
println("start")
println("retries: ${Config.MAX_RETRIES}")
println("slug: ${Config.SLUG}")
println("tags: ${Config.DEFAULT_TAGS}")
val retry = Client::class.java.getAnnotation(Retry::class.java)
println("@Retry(times = ${retry.times})")
}
Output
retries: 3 prints before the init message, because the 3 was copied into main and Config was never touched. The first plain val read, Config.SLUG, runs the object's initializer, and from then on both values are ready. The annotation reads back as @Retry(times = 3). The copying has one catch across libraries: code compiled against a const val keeps the old value until it is recompiled, so a value that may change between releases is safer as a val.
5Related constants: enum class or object
When constants form a fixed set, such as statuses, directions or log levels, an enum class is better than a row of Int constants. A function that takes an HttpStatus can't be handed 42, each entry carries its own data, and a when over all the entries needs no else. Keep an object for constants that are just values sharing a prefix, like colors or keys. Turning text into an entry has its own page: convert a string to an enum.
// enum class: a fixed set of values, each with its own data enum class HttpStatus(val code: Int, val reason: String) { OK(200, "OK"), NOT_FOUND(404, "Not Found"), SERVER_ERROR(500, "Internal Server Error"), } // object: plain named values that belong together object Colors { const val PRIMARY = "#7F52FF" const val ERROR = "#D32F2F" val ALL = listOf(PRIMARY, ERROR) } // No else needed: the compiler knows every entry fun describe(status: HttpStatus): String = when (status) { HttpStatus.OK -> "fine" HttpStatus.NOT_FOUND, HttpStatus.SERVER_ERROR -> "failed" } fun main() { for (status in HttpStatus.entries) { println("${status.code} ${status.reason}: ${describe(status)}") } println(HttpStatus.valueOf("NOT_FOUND").code) println(HttpStatus.entries.first { it.code == 500 }) println(Colors.ALL) }
Output
HttpStatus.entries lists the entries in declaration order, so the loop prints 200 OK: fine first. valueOf("NOT_FOUND") finds an entry by its name and gives 404; looking one up by its data, as the first call does with 500, prints the entry's name, SERVER_ERROR. Older code uses values() in place of entries. The Colors object mixes both kinds: two const val strings, and a val list built from them.
6What Java sees: static final and @JvmField
On the JVM, a const val compiles to a public static final field, exactly what Java writes by hand. A top-level one lands in the file's class (MainKt), a companion one in the outer class. A plain val becomes a private field with a getter, so Java has to write Logger.Companion.getLEVELS(). For a value const doesn't allow, such as a List, @JvmField drops the getter and makes the field itself public, so Java reads Logger.COLORS. The program below asks the JVM what it got. (For functions, the matching tool is @JvmStatic, covered in create a static method.)
import java.lang.reflect.Modifier const val APP_NAME = "Inventory" val startTags = listOf("new") class Logger { companion object { const val TAG = "Logger" val LEVELS = listOf("debug", "info") @JvmField val COLORS = listOf("gray", "blue") } } // Print the static fields the JVM sees, with their modifiers fun fields(c: Class<*>) = c.declaredFields .filter { Modifier.isStatic(it.modifiers) && it.name != "Companion" } .sortedBy { it.name } .forEach { val mods = Modifier.toString(it.modifiers) println("${c.simpleName}.${it.name}: $mods") } fun main() { fields(Class.forName("MainKt")) fields(Logger::class.java) val getters = Logger.Companion::class.java.declaredMethods .map { it.name } .filter { it.startsWith("get") } println("Logger.Companion getters: $getters") }
Output
APP_NAME, TAG and COLORS all come out as public static final; startTags and LEVELS are private static final, and the only getter is [getLEVELS]. The fields of a companion object sit on Logger itself, which is why Java writes Logger.TAG. In Kotlin code none of this matters: Logger.LEVELS reads the same with or without @JvmField. Add it only when Java callers use the value.
7Which should you use?
| Declaration | Known at | Types | Best for |
|---|---|---|---|
| const val X = 3 (top level) | Compile time | Primitives, String | Most constants, a private log TAG |
| object Api { const val … } | Compile time | Primitives, String | Constants grouped under one name |
| companion object { const val … } | Compile time | Primitives, String | Constants that belong to one class |
| enum class | Fixed at compile time | Entries with any data | A fixed set of related values |
| val X = listOf(…) | Run time | Any type | Lists, maps, values a function computes |
| @JvmField val X = … | Run time | Any type | Non-const values Java reads as a field |
Frequently asked questions
What is the difference between const val and val in Kotlin?
Both are read-only. A const val is a compile-time constant: it must be a primitive or a String known when the code compiles, and the compiler copies its value into every place that reads it. A val is set at run time, can hold any type, including a List or the result of a function call, and is read through a getter. Only a const val can be used as an annotation argument.
What is the Kotlin equivalent of Java static final?
A const val, either at the top level of a file or inside an object or companion object. It compiles to a public static final field. For a type const does not allow, such as a list, a val in a companion object marked @JvmField also becomes a public static final field.
Should constants go at the top level or in a companion object?
Prefer the top level: it needs no wrapper and reads as MAX_ITEMS anywhere in the package. Use a companion object when the constant belongs to one class and callers should write ClassName.MAX_ITEMS, or when a file holds several classes that each need their own value, like a log tag. For a const val there is no cost difference, since the value is copied into the caller either way.
How do I define a log TAG constant in Kotlin?
Write private const val TAG = "MyActivity" at the top of the file, above the class. Inside a class that shares its file with others, use companion object { private const val TAG = "MyActivity" } instead. javaClass.simpleName follows renames, but it is computed at run time, so it can only be a plain val, not a const val.
Why can't I make a List a const val?
A const val can only hold a primitive type (Int, Long, Double, Boolean, Char and the rest), an unsigned type or a String. A list is an object created when the program runs, so the compiler stops with Const 'val' has type 'List<Int>'. Only primitive types and 'String' are allowed. Use val PORTS = listOf(80, 443); it is still read-only.
How should Kotlin constants be named?
Kotlin's coding conventions use screaming snake case, MAX_RETRIES, for const val properties and for top-level or object val properties that hold deeply immutable data. A val that holds an object with behavior or mutable state uses camelCase like any other property. Enum entries are usually written the same way: NOT_FOUND.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground