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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With