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?