8 Basic types, collections, and arrays

 

This chapter covers

  • Primitive and other basic types and their correspondence to the Java types
  • Kotlin collections, arrays, and their nullability and interoperability stories

Beyond its support for nullability, Kotlin’s type system has several essential features to improve the reliability of your code and implements many lessons learned from other type systems, including Java’s. These decisions shape the way you work with everything in Kotlin code, from primitive values and basic types to the hierarchy of collections found in the Kotlin standard library. Kotlin introduces features such as read-only collections and refines or doesn’t expose parts of the type system that have turned out to be problematic or unnecessary, such as first-class support for arrays. Let’s take a closer look, starting with the basic building blocks.

8.1 Primitive and other basic types

This section describes the basic types used in programs, such as Int, Boolean, and Any. Unlike Java, Kotlin doesn’t differentiate primitive types and wrappers. You’ll shortly learn why and how it works under the hood. You’ll see the correspondence between Kotlin types and such Java types as Object and Void, as well.

8.1.1 Representing integers, floating-point numbers, characters, and Booleans with primitive types

8.1.2 Using the full bit range to represent positive numbers: Unsigned number types

8.1.3 Nullable primitive types: Int?, Boolean?, and more

8.1.4 Kotlin makes number conversions explicit

8.1.5 Any and Any?: The root of the Kotlin type hierarchy

8.1.6 The Unit type: Kotlin’s void

8.1.7 The Nothing type: “This function never returns”

8.2 Collections and arrays

8.2.1 Collections of nullable values and nullable collections

8.2.2 Read-only and mutable collections

8.2.3 Kotlin collections and Java collections are deeply related

8.2.4 Collections declared in Java are seen as platform types in Kotlin

8.2.5 Creating arrays of objects and primitive types for interoperability and performance reasons

Summary