Search code examples
javajvmkotlinprimitive

Are number operations using Kotlin as fast as the equivalent with Java primitives?


Java has primitives because using them leads to more efficient, readable, and less error prone code than their class based counterparts.

Does Kotlin perform compile time optimizations to ensure that number operations perform at the same level (Or better) as Java primitives would?


Solution

  • Yes, Kotlin uses primitives as well. But note that:

    1. Reasons for "less error-prone" don't really apply in Kotlin: the boxed types aren't nullable unless you ask for it (just like the primitives) and you can't confuse == and equals.

    2. Neither do the "more readable": you can use operators with both.

    3. The "more efficient" part does very much apply, but you can't make the one-character typographical error mentioned in the top answer to the linked question: you have to write java.lang.Long to get the boxed type!

    On the other hand, you need to be aware of IntArray being more efficient than Array<Int> (the correspond to Java int[] and java.lang.Integer[]) despite both appearing to use Int.