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

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

    First of all, the naming convention in Kotlin for constants is the same than in java (e.g : MY_CONST_IN_UPPERCASE).

    How should I create it ?

    1. As a top level value (recommended)

    You just have to put your const outside your class declaration.

    Two possibilities : Declare your const in your class file (your const have a clear relation with your class)

    private const val CONST_USED_BY_MY_CLASS = 1
    
    class MyClass { 
        // I can use my const in my class body 
    }
    

    Create a dedicated constants.kt file where to store those global const (Here you want to use your const widely across your project) :

    package com.project.constants
    const val URL_PATH = "https:/"
    

    Then you just have to import it where you need it :

    import com.project.constants
    
    MyClass {
        private fun foo() {
            val url = URL_PATH
            System.out.print(url) // https://
        }
    }
    

    2. Declare it in a companion object (or an object declaration)

    This is much less cleaner because under the hood, when bytecode is generated, a useless object is created :

    MyClass {
        companion object {
            private const val URL_PATH = "https://"
            const val PUBLIC_URL_PATH = "https://public" // Accessible in other project files via MyClass.PUBLIC_URL_PATH
        }
    }
    

    Even worse if you declare it as a val instead of a const (compiler will generate a useless object + a useless function) :

    MyClass {
        companion object {
            val URL_PATH = "https://"
        }
    }
    

    Note :

    In kotlin, const can just hold primitive types. If you want to pass a function to it, you need add the @JvmField annotation. At compile time, it will be transform as a public static final variable. But it's slower than with a primitive type. Try to avoid it.

    @JvmField val foo = Foo()
    
    0 讨论(0)
  • 2020-12-04 19:04

    Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods.

    public class DbConstants {
        companion object {
            val TABLE_USER_ATTRIBUTE_EMPID = "_id"
            val TABLE_USER_ATTRIBUTE_DATA = "data"
        }
    

    Instead define the constants in object.

    Recommended practice :

    object DbConstants {
            const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
            const val TABLE_USER_ATTRIBUTE_DATA = "data"
    }
    

    and access them globally like this: DbConstants.TABLE_USER_ATTRIBUTE_EMPID

    0 讨论(0)
  • 2020-12-04 19:08

    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"
    

    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"
    
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-04 19:10

    local constants:

    const val NAME = "name"
    

    Global constants:

    object MyConstants{
        val NAME = "name"
        val ID = "_id"
        var EMAIL = "email"
    }
    

    access MyConstants.NAME

    0 讨论(0)
  • 2020-12-04 19:19
    class Myclass {
    
     companion object {
            const val MYCONSTANT = 479
    }
    

    you have two choices you can use const keyword or use the @JvmField which makes it a java's static final constant.

    class Myclass {
    
         companion object {
               @JvmField val MYCONSTANT = 479
        }
    

    If you use the @JvmField annotation then after it compiles the constant gets put in for you the way you would call it in java.
    Just like you would call it in java the compiler will replace that for you when you call the companion constant in code.

    However, if you use the const keyword then the value of the constant gets inlined. By inline i mean the actual value is used after it compiles.

    so to summarize here is what the compiler will do for you :

    //so for @JvmField:
    
    Foo var1 = Constants.FOO;
    
    //and for const:
    
    Foo var1 = 479
    
    0 讨论(0)
提交回复
热议问题