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

更新于:2021-10-27

3K+ 次查看

启动你的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.