官术网_书友最值得收藏!

Primitive data types

In Kotlin, everything is an object (reference type, not primitive type). We don't find primitive types, like the ones we can use in Java. This reduces code complexity. We can call methods and properties on any variable. For example, this is how we can convert the Int variable to a Char:

    var code: Int = 75 
    code.toChar() 

Usually (whenever it is possible), under the hood types such as Int, Long, or Char are optimized (stored as primitive types) but we can still call methods on them as on any other objects.

By default, the Java platform stores numbers as JVM primitive types, but when a nullable number reference (for example, Int?), is needed or generics are involved, Java uses boxed representation. Boxing means wrapping a primitive type into a corresponding boxed primitive type. This means that the instance behaves as an object. Examples of Java boxed representations of primitive types are int versus Integer or a long versus Long Since Kotlin is compiled to JVM bytecode, the same is true here:

    var weight: Int = 12 // 1 
    var weight: Int? = null // 2 
  1. The value is stored as a primitive type.
  2. The value is stored as a boxed integer (composite type).

This means that each time we create a number (Byte, Short, Int, Long, Double, and Float), or with Char, and Boolean, it will be stored as a primitive type unless we declare it as a nullable type (Byte?, Char?, Array?, and so on); otherwise, it will be stored as a boxed representation:

    var a: Int = 1 // 1 
    var b: Int? = null // 2 
    b = 12 // 3 
  1. a is non-nullable, so it is stored as a primitive type.
  2. b is null so it is stored as a boxed representation.
  3. b is still stored as a boxed representation although it has a value.

Generic types cannot be parameterized using primitive types, so boxing will be performed. It's important to remember that using boxed representation (composite type) instead of primary representation can have performance penalties, because it will always create memory overhead compared to primitive type representation. This may be noticeable for lists and arrays containing a huge number of elements, so using primary representation may be crucial for application performance. On the other hand, we should not worry about the type of representation when it comes to a single variable or even multiple variable declarations, even in the Android world where memory is limited.

Now let's discuss the most important Kotlin primitive data types: numbers, characters, Booleans, and arrays.

主站蜘蛛池模板: 鄂州市| 剑阁县| 鄂伦春自治旗| 中西区| 右玉县| 依兰县| 鲁山县| 太康县| 北碚区| 安丘市| 和龙市| 临泉县| 横峰县| 郁南县| 太谷县| 余干县| 剑河县| 高淳县| 榆中县| 太仆寺旗| 扎兰屯市| 开化县| 重庆市| 于田县| 霍州市| 灌南县| 万山特区| 平安县| 佛学| 铁力市| 公安县| 安西县| 堆龙德庆县| 长顺县| 临澧县| 丰台区| 繁峙县| 高密市| 香河县| 浦东新区| 普宁市|