Private Setters
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 9 of 57.
Often outside code should read a property but not change it. private set keeps the getter public and makes only the setter private:
class Counter {
var count = 0
private set
fun increment() {
count++
}
}Inside main:
val c = Counter()
c.increment()
println(c.count)
// c.count = 99 // error: the setter is privateOutput:
1This fits values that may only change through a rule, such as a score that only grows through valid awards:
class Player(val name: String) {
var score = 0
private set
private val _history = mutableListOf<Int>()
val history: List<Int> get() = _history
fun award(points: Int) {
if (points <= 0) return
score += points
_history.add(points)
}
}Inside main:
val p = Player("Ada")
p.award(10)
p.award(-5)
p.award(3)
println(p.score)
println(p.history)Output:
13
[10, 3]The history above shows a common pattern: a private MutableList inside the class, exposed as a read-only List. Callers can read the items but have no add or remove to change them:
private val _items = mutableListOf<String>()
val items: List<String> get() = _items // read-only view
// outside: items.add("x") // error: List has no addA val never changes after creation, not even inside the class. var with private set stays changeable inside the class only. Choose val for values that are fixed for the whole life of the object:
class Order(val id: Int) { // never changes
var status = "new"
private set // changes, but only inside Order
fun ship() { status = "shipped" }
}Challenge
EasyComplete the class Elevator(val topFloor: Int). floor and trips can be read from outside but only changed inside the class (private set). goTo(target) moves between floor 0 and topFloor: a valid move to a different floor updates floor, adds 1 to trips and returns true; an invalid or same-floor move returns false.
The supplied code reads the top floor and then target floors. It prints floor 3 after a move or stay 3 when the move was refused, and finally trips: with the count.
Your code goes in Elevator.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val lift = Elevator(input[0].toInt())
for (line in input.drop(1)) {
val moved = lift.goTo(line.toInt())
println("${if (moved) "floor" else "stay"} ${lift.floor}")
}
println("trips: ${lift.trips}")
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground