Classes and data classes
Hub › Android › Beginner › Classes and data classes
Goal
Model a list item with a data class. After this page you will have the Book type the exit artifact's list will render.
Prerequisites
A class
A class bundles named properties into one type. Kotlin has no new keyword — you call the class like a function:
class Person(val name: String, val age: Int)
fun main() {
val hina = Person("Hina", 31)
println(hina.name) // Hina
println(hina.age) // 31
}- Properties declared in the constructor with
valare read-only and visible from outside (hina.name). - Use
varinstead ofvalif you want to reassign the property after construction.
Print the object itself and you get garbage:
println(hina) // Person@7291c18fThat's the JVM's default toString. To make objects useful as values, mark the class data.
A data class
A data class is a class meant to hold values. The compiler generates toString, equals, hashCode, and copy for you.
data class Book(val title: String, val author: String)
fun main() {
val a = Book("The Pragmatic Programmer", "Hunt & Thomas")
val b = Book("The Pragmatic Programmer", "Hunt & Thomas")
println(a) // Book(title=The Pragmatic Programmer, author=Hunt & Thomas)
println(a == b) // true — structural equality, generated for you
}Rules:
- A data class needs at least one constructor parameter.
- All constructor parameters must be
valorvar.
For everything you can do with classes (inheritance, interfaces, sealed types, generics), see the Kotlin classes reference. At this tier we only need plain data classes.
The type we'll render
This is the type the exit artifact will display:
data class Book(val title: String, val author: String)
val library = listOf(
Book("The Pragmatic Programmer", "Hunt & Thomas"),
Book("Clean Code", "Robert C. Martin"),
Book("Designing Data-Intensive Applications", "Martin Kleppmann"),
Book("The Mythical Man-Month", "Frederick P. Brooks"),
Book("Refactoring", "Martin Fowler"),
)
fun main() {
library.forEach { println("${it.title} — ${it.author}") }
}listOf(...) builds a read-only List<Book>. forEach { ... } calls the lambda once per element with it bound to that element.
Output:
The Pragmatic Programmer — Hunt & Thomas
Clean Code — Robert C. Martin
Designing Data-Intensive Applications — Martin Kleppmann
The Mythical Man-Month — Frederick P. Brooks
Refactoring — Martin FowlerKeep this list — page 11 reuses it inside the Compose app.
Next → What Jetpack Compose is