Kotlin 中的常量是什麼,如何建立它們?
在每種程式語言中,我們都需要一些變數,其值在整個程式中永遠不會改變。在 Kotlin 中也是如此,我們有一個關鍵字來建立這樣的變數,其值在整個程式中將保持不變。為了將值宣告為常量,我們可以在開頭使用 **"const"** 關鍵字。在本文中,我們將學習如何以不同的方式將變數宣告為常量。
示例:頂層宣告
示例
Kotlin const 變數可以在程式語言的頂部宣告,並且可以在整個檔案範圍內使用。
private const val My_TOP_LEVEL_CONST_VAL = "Type 1--> Example of Top Level Constant Value"
fun main()
{
println(My_TOP_LEVEL_CONST_VAL);
}輸出
它將產生以下輸出:
Type 1--> Example of Top Level Constant Value
示例:區域性常量
與任何其他程式語言一樣,在 Kotlin 中,我們也可以宣告一個區域性常量值,它將在指定的範圍內被阻止。在下面的示例中,我們將建立一個區域性常量值。
示例
fun main()
{
val MY_LOCAL_CONST="Type 2-->Example of local const value"
println(MY_LOCAL_CONST);
}輸出
它將產生以下輸出:
Type 2-->Example of local const value
示例:伴隨物件 const
Kotlin 還提供了一個在伴隨物件中建立 const 函式的選項。根據最近的程式設計架構,這並不推薦,因為伴隨物件預設建立自己的 getter() 和 setter() 方法,這可能會導致效能問題。
示例
fun main()
{
println(Student.MY_CONSTANT);
}
class Student(){
companion object{
const val MY_CONSTANT = "Type 3--> Using companion Object"
}
}輸出
它將產生以下輸出:
Type 3--> Using companion Object
示例:物件宣告和直接呼叫
常量變數也可以在物件類中宣告。稍後,可以在程式中透過不同的方式使用此變數。
示例
fun main()
{
println(MyConstant.Const_USING_OBJECT_CLASS);
}
object MyConstant {
const val Const_USING_OBJECT_CLASS = "Type 4-->Example of const using object class"
}輸出
它將產生以下輸出:
Type 4-->Example of const using object class
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP