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

后端 未结 13 1159
不知归路
不知归路 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:24

    If you put your const val valName = valValue before the class name, this way it will creates a

    public static final YourClass.Kt that will have the public static final values.

    Kotlin:

    const val MY_CONST0 = 0
    const val MY_CONST1 = 1
    data class MyClass(var some: String)
    

    Java decompiled:

    public final class MyClassKt {
        public static final int MY_CONST0 = 0;
        public static final int MY_CONST1 = 1;
    }
    // rest of MyClass.java
    

提交回复
热议问题