Categories
Android

What is a Kotlin data class?

In Java, we had to often make classes for our data models. A Kotlin equivalent would be something like this:

package com.example.firstgpslocation

class Person {
    var firstName: String = ""
    var lastName: String = ""
    var age: Int = 0
}

But now in Kotlin we have data classes, like this:

package com.example.firstgpslocation

data class Person(
    var firstName: String,
    var lastName: String,
    var age: Int
)

We can create it from MainActivity.kt with this:

package com.example.firstgpslocation

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        val person = Person("Daniel", "Malone", 27)
    }
}

Accessing data is easy:

        // setup
        val person = Person("Daniel", "Malone", 27)
        
        // access firstName like this
        val firstName = person.firstName

No need for setFirstName, setLastName or getAge. Simply call person.firstName, person.age, etc.

A Kotlin data class can also be nested, as in the following example. Each person has Work, which has a Company.

package com.example.firstgpslocation

data class Person(
    var firstName: String,
    var lastName: String,
    var age: Int,
    var work: Work
) {

    data class Work(
        val company: Company,
        val startDate: Long,
        val endDate: Long,
        val jobTitle: String
    ) {

        data class Company(
            val name: String,
            val founded: Long
        )
    }
}

Data class tips

Although we can create mutable variables in data classes (for example, var name = "Daniel"), it's best to use val instead of var. This guarantees data integrity. Why make them var? You'd make them var if you need to change the variables. So generally it's a good idea to process the data before you create your data class not after.

  • use val not var.
  • process data before creating the data class
  • nest data classes if need be
  • use relational data techniques if possible

By Daniel Malone

Daniel Malone is an Android Developer in Austin, Texas. He enjoys writing code, whether it be HTML, CSS, JavaScript, PHP, Java, XML or Kotlin. Daniel started writing code at age 12. By the time he was 15, he had a technology news website that received about 200 visitors a day. His first computer was a Dell Dimension 3000, with an 80GB hard drive, 512MB RAM and a broken DVD drive.