Kotlin中的常量-创建它们的推荐方法是什么? [英] Constants in Kotlin -- what's a recommended way to create them?

查看:418
本文介绍了Kotlin中的常量-创建它们的推荐方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建议如何在Kotlin中创建常量?命名约定是什么?我没有在文档中找到它.

How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation.

companion object {
    //1
    val MY_CONST = "something"

    //2
    const val MY_CONST = "something"

    //3
    val myConst = "something"
}

还是...?

推荐答案

在Kotlin中,如果要创建应该在该类中使用的局部常量,则可以像下面这样创建

In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below

val MY_CONSTANT = "Constants"

如果您想在kotlin中创建一个公共常量(如Java中的 public static final ),则可以按以下步骤创建它.

And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.

companion object{

     const val MY_CONSTANT = "Constants"

}

这篇关于Kotlin中的常量-创建它们的推荐方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆