liveBook · Manning

Const qualifier

As explained in Kotlin in Action, 2E

The const modifier declares a compile-time constant property of a permitted primitive type or String type.

The const modifier marks a property as a compile-time constant. Use it with a top-level or object property initialized by a primitive value or String when the value must be known during compilation. section 3.2.3 section 12.1.1

Declaring a Java-friendly constant

const val UNIX_LINE_SEPARATOR = "\n" This exposes the Kotlin property to Java as a public static final field, rather than through an accessor method. The equivalent Java declaration is `public static final String UNIX_LINE_SEPARATOR = "\n";`.

Without const, a top-level val is normally exposed to Java through a getter. Adding const makes direct field access natural for Java callers and communicates that the value is fixed at compile time. section 3.2.3

Use const when these conditions apply:

  • Declare the property at the top level or inside an object. section 12.1.1
  • Initialize it with a primitive type or String value. section 3.2.3
  • Supply it where a compile-time value is required, such as an annotation argument. section 12.1.1

Using a constant in an annotation

const val TEST_TIMEOUT = 10L class MyTest { @Test @Timeout(TEST_TIMEOUT) fun testMethod() { /* ... */ } } A regular property cannot be used in this position; the compiler requires `const val` for constant expressions. section 12.1.1

How Kotlin in Action, 2E covers it

How deep it goes
Defines placement, permitted types, initialization constraints, Java representation, and annotation usage without exploring compiler internals.
Examples
Uses UNIX_LINE_SEPARATOR for Java field exposure and TEST_TIMEOUT for a JUnit timeout annotation.
What it assumes
Assumes familiarity with Kotlin properties and annotations while teaching placement, allowed types, and compile-time constraints.
What you can do after
Apply const val to define Java-friendly constants and satisfy annotation arguments requiring compile-time values.
How it connects
Connects top-level properties, Java interoperability, annotations, and compile-time constant expressions.

Also explained in

Compare how 7 books explain const qualifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.