在每种编程语言中,我们都需要一些变量,其值在整个程序中永远不会改变。在 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
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