Kotlin: OOP – code examples
Class with Inheritance
Use case: Bundle data and behavior, e.g. users, products, game characters.
open class Tier(val name: String) {
open fun sprich() = "$name makes a sound"
}
class Hund(name: String) : Tier(name) {
override fun sprich() = "$name says Woof!"
}
fun main() {
println(Hund("Rex").sprich())
}Classes and methods are final by default; open allows inheritance, override overrides. The property name is created directly in the constructor.
Data Class with copy
OOP#data#copy#destructuring
Use case: Data objects (DTOs, configurations, results) without boilerplate.
data class Nutzer(val name: String, val alter: Int)
fun main() {
val ada = Nutzer("Ada", 36)
println(ada)
val aelter = ada.copy(alter = 37)
println(aelter)
println(ada == Nutzer("Ada", 36))
val (name, alter) = aelter
println("$name is $alter")
}equals, hashCode, toString, copy, and destructuring are generated automatically. Output: Nutzer(name=Ada, alter=36), Nutzer(name=Ada, alter=37), true, Ada is 37.
object and companion object
OOP#object#companion#singleton
Use case: Singletons (logger, configuration) and factory functions instead of static members.
class Zaehler private constructor(start: Int) {
var wert = start
private set
fun increment() { wert++ }
companion object {
const val MAX = 100
fun ab(start: Int) = Zaehler(start)
}
}
object Konfiguration {
val version = "1.0"
}
fun main() {
val z = Zaehler.ab(5)
z.increment()
println("${z.wert} ${Zaehler.MAX} ${Konfiguration.version}")
}The constructor is private; instances are created via the factory in the companion object. object creates a singleton. Output: 6 100 1.0.