Q:

Kotlin program | Example of compile-time constant

belongs to collection: Kotlin Class and Object Programs

0

Compile-time Constant

  • 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program for compile-time constant in Kotlin

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Example of constructor overloadin... >>
<< Kotlin program | Companion object features...