Kotlin data classes and sealed interfaces
A data class generates equals, hashCode, toString, copy, and componentN functions from its constructor properties. Two data class instances with the same values are equal, and copy makes a new instance with some properties changed. They are the usual way to model plain data in Kotlin.
Kotlin
import java.util.Locale
sealed interface Shape
data class Circle(val radius: Double) : Shape
data class Rectangle(val width: Double, val height: Double) : Shape
fun area(shape: Shape): Double = when (shape) {
is Circle -> Math.PI * shape.radius * shape.radius
is Rectangle -> shape.width * shape.height
}
fun main() {
val shapes = listOf(Circle(1.5), Rectangle(2.0, 3.5))
for (shape in shapes) {
println(String.format(Locale.ROOT, "%s -> %.2f", shape, area(shape)))
}
val circle = Circle(2.0)
val bigger = circle.copy(radius = 3.0)
println(circle == Circle(2.0))
println(bigger)
val (width, height) = Rectangle(4.0, 5.0)
println(width * height)
}