Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can be expressed in a compile-time constant (const val)?

Tags:

kotlin

The documentation for compile-time constants lists three requirements that the property needs to fulfill in order to declare it as a const val. These are:

  • Top-level or member of an object
  • Initialized with a value of type String or a primitive type
  • No custom getter

The "No custom getter" requirement leads me to believe that I cannot use any functions in a constant declaration, but this seems not to be the case. These compile:

const val bitmask = (5 shl 3) + 2
const val aComputedString = "Hello ${0x57.toChar()}orld${((1 shl 5) or 1).toChar()}"
const val comparedInt = 5.compareTo(6)
const val comparedString = "Hello".compareTo("World!")
const val toStringedInt = 5.compareTo(6).toString()
const val charFromString = "Hello World!".get(3)

However, these will not compile:

// An extension function on Int.
const val coercedInt = 3.coerceIn(1..5)

// Using operator syntax to call the get-function.
const val charFromString = "Hello World!"[3]

// An immediate type is not a primitive.
const val stringFromImmediateList = "Hello World!".toList().toString()

// Using a function defined by yourself.
fun foo() = "Hello world!"
const val stringFromFunction = foo()

What are the exact rules for compile-time constants?

Is there a list of functions I can use in a compile-time constant declaration?

like image 393
marstran Avatar asked Sep 05 '25 06:09

marstran


1 Answers

There is no exact documentation on this, but list of functions that can be used in the constant expressions can be found in the compiler sources here. Note that only those functions can be used in constant expressions that are defined under the kotlin package, on custom overloaded operators compiler will report errors.

like image 192
Mikhail Zarechenskiy Avatar answered Sep 08 '25 03:09

Mikhail Zarechenskiy