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 typeNo 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 constantconst val PI=3.14//Declare Class with object to make singletonobject Physics{//declare compile time constantconst val GRAVITY=10}//declare classclass Greetings{//declare companion objectcompanion object{//declare compile time constantconst val GREET="Hello IncludeHelp"}}//Main Function, Entry Point of Programfun main(){//Print All Constant Valueprintln("PI Value : $PI")println("Gravity : ${Physics.GRAVITY}")println("Greetings: ${Greetings.GREET}")}
Output:
输出:
PI Value : 3.14Gravity : 10Greetings: Hello IncludeHelp
翻译自: /kotlin/example-of-compile-time-constant.aspx
kotlin 编译时常量
如果觉得《kotlin 编译时常量_Kotlin程序| 编译时常量示例》对你有帮助,请点赞、收藏,并留下你的观点哦!