Classes, Constructors & Properties
What is a class?
A class is a blueprint for creating objects. It bundles together data (properties) and behaviour (functions). An object is one instance built from that blueprint.
class Car {
var brand: String = ""
var speed: Int = 0
fun accelerate(by: Int) {
speed += by
}
}
val car = Car() // create an instance
car.brand = "Tata"
car.accelerate(20)
println(car.speed) // 20
The primary constructor
Kotlin lets you declare properties right in the constructor — this removes the boilerplate Java needs.
class Car(val brand: String, var speed: Int = 0) {
fun accelerate(by: Int) { speed += by }
}
val car = Car("Tata")
val car2 = Car("BMW", 60)
Here val brand and var speed in the parentheses become properties automatically. speed even has a default value.
init blocks
Need to run setup code when an object is created? Use an init block:
class Account(val owner: String, balance: Double) {
var balance = balance
private set // others can read but not write
init {
require(balance >= 0) { "Balance cannot be negative" }
}
}
Custom getters and setters
Properties can compute their value or validate changes:
class Rectangle(val width: Int, val height: Int) {
val area: Int
get() = width * height // computed each time it's read
}
class Temperature {
var celsius: Double = 0.0
set(value) {
field = value // 'field' is the backing storage
}
val fahrenheit get() = celsius * 9 / 5 + 32
}
Secondary constructors
class Person(val name: String) {
var age: Int = 0
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
Common mistakes
- Writing Java-style getters/setters by hand — Kotlin properties already do this.
- Exposing a mutable property when callers should only read it — use
private set. - Putting heavy logic in
init— keep object creation cheap.
Summary: Declare properties in the primary constructor, use init for setup/validation, and custom getters for computed values. Kotlin removes nearly all getter/setter boilerplate.