Constants in Kotlin — what's a recommended way to create them?

后端 未结 13 1153
不知归路
不知归路 2020-12-04 18:45

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         


        
13条回答
  •  情深已故
    2020-12-04 19:20

    You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const.

    So, in this case, it should be:

    const val MY_CONST = "something"

    and then you can import the constant using:

    import package_name.MY_CONST

    You can refer to this link

提交回复
热议问题