kotlin 编译时常量_Kotlin程序| 编译时常量示例
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 constantconst val GRAVITY=10 }//declare class class Greetings{//declare companion objectcompanion object{//declare compile time constantconst val GREET="Hello IncludeHelp"} }//Main Function, Entry Point of Program fun main(){//Print All Constant Valueprintln("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 編譯時常量
總結
以上是生活随笔為你收集整理的kotlin 编译时常量_Kotlin程序| 编译时常量示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用python学线性代数_二项式过程|
- 下一篇: 小米手环无法模拟门卡_颜值与功能得到全面