AnyCompiler

Classes and Objects

Kotlin lets you declare a class's fields directly in its primary constructor — class Dog(val name: String, val age: Int) declares both name and age as read-only properties and wires up the constructor to set them, all in a single line. Compare this to the multi-line field-plus-constructor boilerplate every other class-based language on this site needs.

class Dog(val name: String, val age: Int)

fun main() {
    val d = Dog("Rex", 3)
    println("${d.name} is ${d.age}")
}
Output
Rex is 3

Next: data classes — getting equals, hashCode, toString, and more for free, something Java on this site has no equivalent for.

Practice exercise

Define a class Book with primary-constructor properties title (String) and pages (Int). Create a Book with title "Dune" and pages 412, then print both.