Classes, Data Classes and Objects
Harry
· 14 Sep 2026
· 2 views
Advertisement
Classes and constructors
Kotlin folds the constructor and property declarations into the class header:
class Person(val name: String, var age: Int) {
fun birthday() { age++ }
}
val p = Person("Ada", 36) // no 'new' keyword
p.birthday()
val name in the header declares a read-only property and assigns it from the constructor argument – one line replaces a field, a constructor parameter and a getter.
Data classes
Classes that just hold data are declared with data class. The compiler generates equals(), hashCode(), toString(), copy() and destructuring for you:
data class User(val name: String, val age: Int)
val u = User("Ada", 36)
println(u) // User(name=Ada, age=36)
val older = u.copy(age = 37) // copy with one field changed
val (n, a) = u // destructuring
Singletons with object
The object keyword declares a singleton in one step – no static, no manual instance management:
object AppConfig {
val version = "1.0"
fun printInfo() = println("Version $version")
}
AppConfig.printInfo()
Interfaces and inheritance
Classes are final by default; mark a class open to allow subclassing. Interfaces work as in Java but can hold default method bodies:
interface Shape { fun area(): Double }
open class Base
class Circle(val r: Double) : Base(), Shape {
override fun area() = Math.PI * r * r
}
Key points
- Primary constructors and properties are declared in the class header – no boilerplate.
data classgenerates equals/hashCode/toString/copy and destructuring.objectdeclares a singleton directly.- Classes are final by default; use
opento allow inheritance.