Kotlin program | Example of compile-time constant

Kotlin | Compile-time Constant: Here, we are implementing a Kotlin program to demonstrate the example of compile-time constant.
Submitted by IncludeHelp, on June 03, 2020

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.

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}")


PI Value : 3.14
Gravity  : 10
Greetings: Hello IncludeHelp

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.