Chapter 6. The Kotlin type system

 

This chapter covers

  • Nullable types and syntax for dealing with nulls
  • Primitive types and their correspondence to the Java types
  • Kotlin collections and their relationship to Java

By now, you’ve seen a large part of Kotlin’s syntax in action. You’ve moved beyond creating Java-equivalent code in Kotlin and are ready to enjoy some of Kotlin’s productivity features that can make your code more compact and readable.

Let’s slow down a bit and take a closer look at one of the most important parts of Kotlin: its type system. Compared to Java, Kotlin’s type system introduces several new features that are essential for improving the reliability of your code, such as support for nullable types and read-only collections. It also removes some of the features of the Java type system that have turned out to be unnecessary or problematic, such as first-class support for arrays. Let’s look at the details.

6.1. Nullability

Nullability is a feature of the Kotlin type system that helps you avoid NullPointer-Exception errors. As a user of a program, you’ve probably seen an error message similar to “An error has occurred: java.lang.NullPointerException,” with no additional details. Another version is a message like “Unfortunately, the application X has stopped,” which often also conceals a NullPointerException as a cause. Such errors can be troublesome for both users and developers.

6.2. Primitive and other basic types

6.3. Collections and arrays

6.4. Summary

sitemap