Chapter 4. Classes, objects, and interfaces

 

This chapter covers

  • Classes and interfaces
  • Nontrivial properties and constructors
  • Data classes
  • Class delegation
  • Using the object keyword

This chapter gives you a deeper understanding of working with classes in Kotlin. In chapter 2, you saw the basic syntax for declaring a class. You know how to declare methods and properties, use simple primary constructors (aren’t they nice?), and work with enums. But there’s more to see.

Kotlin’s classes and interfaces differ a bit from their Java counterparts: for example, interfaces can contain property declarations. Unlike in Java, Kotlin’s declarations are final and public by default. In addition, nested classes aren’t inner by default: they don’t contain an implicit reference to their outer class.

For constructors, the short primary constructor syntax works great for the majority of cases, but there’s also the full syntax that lets you declare constructors with nontrivial initialization logic. The same works for properties: the concise syntax is nice, but you can easily define your own implementations of accessors.

The Kotlin compiler can generate useful methods to avoid verbosity. Declaring a class as a data class instructs the compiler to generate several standard methods for this class. You can also avoid writing delegating methods by hand, because the delegation pattern is supported natively in Kotlin.

4.1. Defining class hierarchies

4.2. Declaring a class with nontrivial constructors or properties

4.3. Compiler-generated methods: data classes and class delegation

4.4. The “object” keyword: declaring a class and creating an instance, combined

4.5. Summary

sitemap