What is the equivalent of Java static final fields

2019-01-10 20:26发布

问题:

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

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

What is the equivalent in Kotlin?

回答1:

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
    }
}


回答2:

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
}


回答3:

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{
}


标签: java kotlin