Primitive types in Java, Kotlin

There is no primitive type in Kotlin. Everything is an object in it. Java still uses this type because of performance. 

We can find a question on the Stackoverflow, "Why do people still use primitive types in Java?"

In Joshua Block's Effective Java, "Avoid creating unnecessary objects"

public static void main(String[] args) {
    Long sum = 0L; // uses Long, not long
    for(long i = 0; i <= Integer.MAX_VALUE; i++) {
        sum += i;
    }
    System.out.println(sum);
}
public static void main(String[] args) {
    long sum = 0L; // uses long
    for(long i = 0; i <= Integer.MAX_VALUE; i++) {
        sum += i;
    }
    System.out.println(sum);
}

Did you notice that? The only difference between two codes is the type. First one reportedly takes 43 seconds to run, and the second takes 8. 

In kotlin, the language only knows objects like Int, Float, Boolean.. so on. So thinks like boxing are nothing to be concerned about in Kotlin.

If you afraid this comes with bad performance, rest assured the Kotiln compiler tries hard to make use of Java's primitives in compiled code whenever possible, for improved performance. 

 

 

youngdeok's picture

Language

Get in touch with us

"If you would thoroughly know anything, teach it to other."
- Tryon Edwards -