๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Visibility Modifiers

Visibility modifiers are keywords that control where a class member can be used.

Three modifiers in one class

code is private and read inside the class. hint is protected and read in the subclass, and revealHint is internal and called from main in the same module.

open class Vault(private val code: String, protected val hint: String) {
    fun matches(guess: String): Boolean {
        return guess == code
    }

    internal fun revealHint(): String {
        return hint
    }
}

class SmallVault : Vault("1234", "low numbers") {
    fun tryHint(): String {
        return hint
    }
}

fun main() {
    val v = SmallVault()
    println(v.matches("1234"))
    println(v.matches("0000"))
    println(v.tryHint())
    println(v.revealHint())
}

Public is the default

label carries no modifier, so main reads it directly. Members are public unless a modifier says otherwise.

class Box(val label: String) {
    fun show(): String {
        return label
    }
}

fun main() {
    val b = Box("tools")
    println(b.label)
    println(b.show())
}

A private set

count reads as a normal public property. Only the step function inside the class can change it.

class Counter {
    var count: Int = 0
        private set

    fun step() {
        count += 1
    }
}

fun main() {
    val c = Counter()
    c.step()
    c.step()
    println(c.count)
}

Reading a private member fails

The last line reads code from outside the class. The compiler refuses because code is private in Vault.

class Vault(private val code: String) {
    fun show(): String {
        return code
    }
}

fun main() {
    val v = Vault("1234")
    println(v.code)
}

Example

open class Account(private val pin: String) {
    protected var balance: Int = 0

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

    fun checkPin(guess: String): Boolean {
        return guess == pin
    }
}

class SavingsAccount : Account("42") {
    fun showBalance(): Int {
        return balance
    }
}

fun main() {
    val a = SavingsAccount()
    a.deposit(50)
    println(a.showBalance())
    println(a.checkPin("42"))
    println(a.checkPin("00"))
}

Key points

  • A member with no modifier is public, and any code can use it.
  • private limits a member to code inside its own class.
  • protected limits a member to its class and subclasses of that class.
  • internal limits a member to code in the same module.
  • A property can pair a public read with a private set.

In this example, pin stays private and only checkPin inside Account reads it. balance is protected, so the subclass reads it in showBalance. The deposit call adds 50 before the balance prints.

Note

private set lets the class change a value that outside code can only read.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

Which modifier keeps a member usable only inside its own class?