If the value of a read-only (immutable) property is known at the compile time.
Mark it as a compile-time constant using the const modifier.
Such properties must be fulfilled by the following requirements.
Top-level, or member of an object declaration or a companion object.
Initialized with a value of type String or a primitive type
No custom getter
No run time assignment allowed into const variables.
The val keyword also used to make property immutable but the main difference between const and val is that properties declare with val can be initialized at runtime.
package com.includehelp
//declare Top Level compile time constant
const val PI=3.14
//Declare Class with object to make singleton
object Physics{
//declare compile time constant
const val GRAVITY=10
}
//declare class
class Greetings{
//declare companion object
companion object{
//declare compile time constant
const val GREET="Hello IncludeHelp"
}
}
//Main Function, Entry Point of Program
fun main(){
//Print All Constant Value
println("PI Value : $PI")
println("Gravity : ${Physics.GRAVITY}")
println("Greetings: ${Greetings.GREET}")
}
Output:
PI Value : 3.14
Gravity : 10
Greetings: Hello IncludeHelp
Program for compile-time constant in Kotlin
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer