What is the equivalent of Java static final fields in Kotlin?

后端 未结 3 1593
囚心锁ツ
囚心锁ツ 2020-11-29 23:24

In Java, to declare a constant, you do something like:

class Hello {
    public static final int MAX_LEN = 20;
}

What is the equivalent in Ko

3条回答
  •  清歌不尽
    2020-11-29 23:57

    According Kotlin documentation this is equivalent:

    class Hello {
        companion object {
            const val MAX_LEN = 20
        }
    }
    

    Usage:

    fun main(srgs: Array) {
        println(Hello.MAX_LEN)
    }
    

    Also this is static final property (field with getter):

    class Hello {
        companion object {
            @JvmStatic val MAX_LEN = 20
        }
    }
    

    And finally this is static final field:

    class Hello {
        companion object {
            @JvmField val MAX_LEN = 20
        }
    }
    

提交回复
热议问题