Kotlin · Course navigation

Kotlin Classes

Declare a class with a primary constructor and private state.

On this page
Before you start

Kotlin functions.

  • Declare a class with a primary constructor and private state.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A Kotlin class can declare its properties right in the primary constructor. val makes a read-only property and var a mutable one, and marking it private hides it from code outside the class.

Here owner is readable by anyone, while balance can only be changed by the class itself through deposit. There is no new keyword: Account("Ada", 100) calls the constructor directly. The string template "$owner has $balance" inserts both values.

Code example

Kotlin
class Account(val owner: String, private var balance: Int) {
    fun deposit(amount: Int) {
        balance += amount
    }

    fun report(): String = "$owner has $balance"
}

fun main() {
    val account = Account("Ada", 100)
    account.deposit(50)
    println(account.report())
}
Output
Ada has 150

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1class Account(val owner: String, private var balance: Int) {
2 fun deposit(amount: Int) {
3 balance += amount
4 }
5
6 fun report(): String = "$owner has $balance"
7}
8
9fun main() {
10 val account = Account("Ada", 100)
11 account.deposit(50)
12 println(account.report())
13}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
The constructor creates two properties: a public owner and a private balance.—
—
Create the object.balance = 100
—
Add to the private balance through a method.balance = 150
—
Format and print the report.balance = 150
Ada has 150

Behind the scenes

How Kotlin processes this code

Kotlin commonly compiles to JVM bytecode, which the JVM executes.

Cost and common mistakes

O(1) per method call.

  • Reading account.balance outside the class is a compile error because it is private.
  • A val property cannot be reassigned after construction.

Try it yourself

What does account.deposit(-20) do here?

Reveal answer and reasoning

Nothing prevents it, so the balance drops to 130. Add a check inside deposit to reject negative amounts.

Further reading