Classes & Objects

Kotlin classes fold constructor, fields, and getters into one line in the class header — and creating an object needs no new keyword at all.

Defining a class

A class's constructor parameters can go directly in the class header, and val/var there automatically become properties — no separate field declarations or constructor body needed:

</> main.kt
class BankAccount(val owner: String, var balance: Double) {
    fun deposit(amount: Double) {
        balance += amount
        println("Deposited $amount. New balance: $balance")
    }
}

fun main() {
    val account = BankAccount("Jamie", 100.0)
    account.deposit(50.0)
}
Output
Deposited 50.0. New balance: 150.0

Compare this to Java or even C#, where the same class needs explicit fields, a constructor that assigns each one, and getters — Kotlin's primary constructor syntax collapses all of that into the class header itself.

Creating objects

There's no new keyword — calling the class name like a function creates an instance:

</> main.kt
fun main() {
    val account1 = BankAccount("Jamie", 100.0)
    val account2 = BankAccount("Sasha", 500.0)

    account1.deposit(25.0)

    println("${account1.owner}: ${account1.balance}")
    println("${account2.owner}: ${account2.balance}")
}
Output
Deposited 25.0. New balance: 125.0
Jamie: 125.0
Sasha: 500.0

Depositing into account1 leaves account2 completely untouched — they're independent objects, same as in any other object-oriented language.

Note: owner was declared with val and balance with var right in the constructor — that single choice controls whether each property is read-only or mutable from outside the class. account1.owner = "New Name" wouldn't compile, but account1.balance = 500.0 would, since balance is a var.