Kotlin 2 cheatsheet
Kotlin 2: Classes and types
7 common Kotlin 2 tasks.
Data classes
A data class gets equals, hashCode, toString, copy and destructuring for free.
data class User(val id: Int, val name: String)
val ada = User(1, "Ada")
val renamed = ada.copy(name = "Ada Lovelace")
val (id, name) = ada
Classes and constructors
The primary constructor is part of the class header. Properties can have getters.
class Account(val owner: String, balance: Int = 0) {
var balance = balance
private set
fun deposit(amount: Int) { balance += amount }
}
Sealed types for fixed alternatives
A sealed interface limits its implementations, so when must handle every case.
sealed interface Result {
data class Success(val value: Int) : Result
data class Failure(val message: String) : Result
}
fun show(r: Result) = when (r) {
is Result.Success -> "ok ${r.value}"
is Result.Failure -> "error ${r.message}"
}
Singletons and companion objects
object declares a singleton, and a companion object holds class-level members.
object Config { const val VERSION = "1.0" }
class User private constructor(val name: String) {
companion object {
fun create(name: String) = User(name.trim())
}
}
Add a function to an existing type
An extension function is called like a member but defined outside the class.
fun String.isPalindrome() = this == reversed()
println("level".isPalindrome())
Interfaces and delegation
Implement an interface by delegating to another object with by.
interface Logger { fun log(message: String) }
class ConsoleLogger : Logger { override fun log(message: String) = println(message) }
class Service(logger: Logger) : Logger by logger
Compute a value on first use
lazy runs its block once, the first time the property is read.
val config by lazy { loadConfig() }