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
notvar
. - process data before creating the
data class
- nest
data class
es if need be - use relational data techniques if possible