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

后端 未结 13 1160
不知归路
不知归路 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()
    

提交回复
热议问题