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

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

    Like val, variables defined with the const keyword are immutable. The difference here is that const is used for variables that are known at compile-time.

    Declaring a variable const is much like using the static keyword in Java.

    Let's see how to declare a const variable in Kotlin:

    const val COMMUNITY_NAME = "wiki"
    

    And the analogous code written in Java would be:

    final static String COMMUNITY_NAME = "wiki";
    

    Adding to the answers above -

    @JvmField an be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.

     @JvmField
     val COMMUNITY_NAME: "Wiki"
    

    Static fields

    Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.

    Usually these fields are private but they can be exposed in one of the following ways:

    • @JvmField annotation;
    • lateinit modifier;
    • const modifier.

    More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields

提交回复
热议问题