Kotlin Tutorial · Object-Oriented Kotlin · Lesson 12 of 31

Kotlin Classes and Properties

Define classes with primary constructors, properties, init blocks, custom getters and visibility modifiers.

Create a free account to save this page, take notes and track your progress. Sign in

Primary constructors

The class header declares the primary constructor; val/var parameters become properties. There's no new keyword.

Primary constructor and init
class Product(val name: String, var price: Double, val tags: List<String> = emptyList()) {
    init {
        require(price >= 0) { "price must not be negative" }
    }

    fun discounted(percent: Int): Double = price * (100 - percent) / 100
}

fun main() {
    val mug = Product("Mug", 12.0)
    println("${mug.name} costs ${mug.price}")
    mug.price = 10.0
    println(mug.discounted(20))
    println(runCatching { Product("Bad", -1.0) }.exceptionOrNull()?.message)
}

Output

Mug costs 12.0
8.0
price must not be negative

Run this on your computer — see “Get Started” for setup.

Getters, setters and visibility

Properties can have custom getters and setters (field is the stored value). Members are public by default; private, protected and internal (visible in the same module) restrict them.

Custom accessors and private set
class BankAccount(val owner: String) {
    var balance: Double = 0.0
        private set                         // readable everywhere, writable only inside the class

    val isOverdrawn: Boolean
        get() = balance < 0                 // computed on every access

    var note: String = ""
        set(value) { field = value.trim() }

    fun deposit(amount: Double) {
        balance += amount
    }
}

fun main() {
    val account = BankAccount("Ana")
    account.deposit(50.0)
    account.note = "   savings  "
    println("${account.owner}: ${account.balance}, overdrawn=${account.isOverdrawn}, note='${account.note}'")
    // account.balance = 1e6            // error: the setter is private
}

Output

Ana: 50.0, overdrawn=false, note='savings'

Run this on your computer — see “Get Started” for setup.

Test yourself

What does class User(val name: String) give you?

  1. A data class
  2. A class with a constructor parameter that is also a read-only property
  3. A private field only
  4. An interface
Show answer

Answer: A class with a constructor parameter that is also a read-only property

Was this page helpful?