Search code examples
kotlinconstantsprimitive

Difference between primitive companion constants and java wrapper constant


Kotlin redefines a number of primitive constants that are already defined in Java, such as Long.MAX_VALUE or Double.NaN.

What is the a difference between them and which should be preferred when coding in Kotlin?

To be clear, I'm referring, for example, to:

kotlin.Long.Companion.MAX_VALUE
java.lang.Long.MAX_VALUE

Solution

  • This is a general phenomenon: a large part of Kotlin standard library is basically the same as in Java. This is so that

    1. Kotlin can provide more precise types: nullable vs non-nullable or List vs MutableList;

    2. This part of the library can be accessed from Kotlin-JS or Kotlin-Native, or other future Kotlin implementations.

    For both reasons, stick with the Kotlin standard library types and methods unless you have some specific need to use the Java ones.

    Long (and Int, etc.) are even something of a special case, because they correspond to more than one Java type: in some contexts they end up as the primitive (long), in others as its boxed version (java.lang.Long). You mostly don't care about this difference in Kotlin, so there's even better reason to keep using kotlin.Long.