Part 07 / Topic 6 of 7
Visibility modifiers
Kotlin has four visibility modifiers; without inheritance yet (that needs protected, which
only makes sense once there's a subclass to share state with -- Stage 2, Part 9), three of them
already cover almost everything a Stage 1 program needs.
| Modifier | Visible from | Typical use |
|---|---|---|
(none, the default) public |
anywhere the class itself is visible | the normal API of the class |
internal |
anywhere in this same module | shared across your whole app, but not exposed to other modules/libraries that depend on it |
private |
only inside this class's own body | implementation details -- bookkeeping, helpers |
class BankAccount(val accountHolder: String, openingBalance: Double) {
// public (the default): visible everywhere this class is visible
var balance: Double = openingBalance
private set
// internal: here, everything compiled by this one kotlinc invocation counts as one
// module, so main() can still reach it -- but a different module/library that merely
// depends on this one would not see it
internal var branchCode: String = "PUNE-MAIN"
// private: not reachable from outside this class, not even from other code in this file
private val transactionLog = mutableListOf<String>()
fun deposit(amount: Double) {
require(amount > 0.0) { "deposit amount must be positive" }
balance += amount
transactionLog.add("deposit ₹$amount")
}
fun printLog() {
println("$accountHolder's log ($branchCode): $transactionLog")
}
}
val account = BankAccount("Asha Kulkarni", 1000.0)
println("Balance: ${account.balance}")
println("Branch before transfer: ${account.branchCode}")
account.branchCode = "MUMBAI-FORT"
println("Branch after transfer: ${account.branchCode}")
account.deposit(250.0)
account.printLog()
Balance: 1000.0
Branch before transfer: PUNE-MAIN
Branch after transfer: MUMBAI-FORT
Asha Kulkarni's log (MUMBAI-FORT): [deposit ₹250.0]
Uncommenting account.transactionLog in main() fails to compile with error: cannot access 'val transactionLog: MutableList<String>': it is private in 'BankAccount' -- checked for real,
not assumed, by trying it in a throwaway two-line class:
$ kotlinc check_private.kt -include-runtime -d check.jar
check_private.kt:6:15: error: cannot access 'val secret: Int': it is private in 'Demo'.
println(d.secret)
^^^^^^
Full program: examples/06_visibility_modifiers.kt.
Done here? The practice set for Part 7 — including the solutions — is on the part page.