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

后端 未结 3 1574
囚心锁ツ
囚心锁ツ 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<String>) {
        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
        }
    }
    
    0 讨论(0)
  • 2020-11-30 00:12

    For me

    object Hello {
       const val MAX_LEN = 20
    }
    

    was to much boilerplate. I simple put the static final fields above my class like this

    val MIN_LENGTH = 10
    
    class MyService{
    }
    
    0 讨论(0)
  • 2020-11-30 00:15

    if you have an implementation in Hello, use companion object inside a class

    class Hello {
      companion object {
        val MAX_LEN = 1 + 1
      }
    
    }
    

    if Hello is a pure singleton object

    object Hello {
      val MAX_LEN = 1 + 1
    }
    

    if the properties are compile-time constants, add a const keyword

    object Hello {
      const val MAX_LEN = 20
    }
    

    if you want to use it in Java, add @JvmStatic annotation

    object Hello {
      @JvmStatic val MAX_LEN = 20
    }
    
    0 讨论(0)
提交回复
热议问题