🚙 · Compile-time constants

2 min read · Updated on by

A short note on compile time constants and their usage in annotations.

If the value of a read-only property is known at compile time, you can mark it as a compile time constant using the const modifier.

Such a property needs to fulfill the following requirements:

  • It must be a top-level property, or a member of an object declaration or a companion object (more on both of those later)
  • It must be initialized with a value of type String or a primitive type
  • It cannot have a custom getter (and, since it’s a constant, it naturally can’t have a setter either)

Such properties can be used in annotations:


//sampleStart
const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"
@Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { }
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the storyteller's code book,
        With concise narratives, a captivating look.
        From variables to functions , a plot so tight,
        In the world of development, it shows its might!
    """.trimIndent()
    println(poem)
}

It might be worth to emphasize the differences between val and const val at this point:

val

  • Value is determined at runtime, e.g. val now = Instant.now()
  • Can be defined anywhere a variable declaration is legal
  • Can be initialized with any legal expression

const val

  • Value is determined at compile time — it is an actual constant, like PI
  • Can only be defined on the top-level or inside an object (more about those later)
  • Can only be initialized with String or a primitive type

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer