Kotlin: Classes Cheat Sheet

Primary constructor

val declares a read-only property, var a mutable one

class Person(val name: String, var age: Int) – name is read-only, age is mutable

Inheritance

open class Person(val name: String) {
    open fun hello() = "Hello, I am $name"
    // Final by default so we need open
}
class PolishPerson(name: String) : Person(name) {
   override fun hello() = "DzieƄ dobry, jestem $name"
}

Properties with assessors

class Person(var name: String, var surname: String) {
    var fullName: String
    get() = "$name $surname"
    set(value) {
        val (rst, rest) = value.split(" ", limit = 2)
        name = rst
        surname = rest
    }
}

Data classes

data class Person(val name: String, var age: Int)
val mike = Person("Mike", 23)

Modifier data adds:

toString that displays all primary constructor properties

print(mike.toString()) // Person(name=Mike, age=23)

equals that compare all primary constructor properties

print(mike == Person("Mike", 23)) // True
print(mike == Person("Mike", 21)) // False

hashCode that is based on all primary constructor properties

val hash = mike.hashCode()
print(hash == Person("Mike", 23).hashCode()) // True
print(hash == Person("Mike", 21).hashCode()) // False

component 1, component2 etc. that allows deconstruction

val (name, age) = mike
print("$name $age") // Mike 23

copy that returns a copy of the object with concrete properties changed

val jake = mike.copy(name = "Jake")

Leave a Reply

Your email address will not be published. Required fields are marked *