Data Class

One of the reasons why Kotlin has taken off in popularity — particularly for Android app development — is that Java can be tedious to write.

One way that developers have tried to reduce that tedium is through annotation processors that generate Java code for you. A classic example of that is Google’s AutoValue. AutoValue is for immutable objects, ones whose fields have getters but no setters. In particular, AutoValue can code-generate things like an equals() method that takes all of the fields into account.

In Kotlin, a data class offers the same basic feature set as AutoValue, with simpler syntax, because it is “baked into” the language itself.

How You Declare It

All you do is add the data keyword to the class declaration:

data class Animal(val species: String, val ageInYears: Float)

The class needs to have 1+ parameters in its constructor, and those parameters need to be declared as val or var… and typically you will use val.

And that’s pretty much it. You are welcome to have whatever functions you need on the class, but nothing else is required.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.