Kotlin Classes
Declare a class with a primary constructor and private state.
On this page
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
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())
}Ada has 150
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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())}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
| Step / line | What happens | State after step | Output 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.