kotlin 编译时常量

编译时常数 (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.

    使用const修饰符将其标记为编译时常量。

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

    不允许将运行时分配分配给const变量。

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

    val关键字还用于使属性不可变,但是const和val之间的主要区别在于,可以在运行时初始化使用val声明的属性。

Kotlin中的编译时常数程序 (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


翻译自: https://www.includehelp.com/kotlin/example-of-compile-time-constant.aspx

kotlin 编译时常量

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐