Object Declarations
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 12 of 57.
object Name { ... } declares a class and its only instance in one step. You use the object by its name; there is no constructor to call:
object AppConfig {
var theme = "light"
val version = "1.4"
fun describe() = "v$version, $theme theme"
}Inside main:
println(AppConfig.describe())
AppConfig.theme = "dark"
println(AppConfig.describe())Output:
v1.4, light theme
v1.4, dark themeThere is exactly one instance, so every part of the program that uses the object reads and changes the same state. The object is created the first time it is used, which the init block below shows:
object Visits {
var count = 0
private set
init { println("Visits created") }
fun record() { count++ }
}
fun home() = Visits.record()
fun about() { Visits.record(); Visits.record() }Inside main:
println("start")
home()
about()
println(Visits.count)Output:
start
Visits created
3An object has no constructor, because nobody creates it. Its properties get their values in their declarations or in init. Apart from that it is a normal class body: private state, private helpers and public methods:
object IdGenerator {
private var next = 1
fun newId(prefix: String) = "$prefix-${pad(next++)}"
private fun pad(n: Int) = n.toString().padStart(3, '0')
}Inside main:
println(IdGenerator.newId("user"))
println(IdGenerator.newId("order"))Output:
user-001
order-002Use an object for something there is exactly one of in a program: a registry, the configuration, a group of helper functions. An object is global state that any file can change, so keep its setters private and let its methods check every change.
object Units {
fun kmToMiles(km: Double) = km * 0.621371
}
Units.kmToMiles(10.0) // called through the name
// val u = Units() // error: an object has no constructorChallenge
EasyComplete the object Leaderboard. It keeps each player's points in a private map. add(player, points) adds points, top() returns the leader as ada 6 (on equal points the name that comes first alphabetically) or empty when nobody has points, reset() removes everyone, and the property players is the number of players.
The helper functions recordWin and recordDraw in Functions.kt are supplied: they use Leaderboard from another file. The supplied code reads commands win ada, draw ada bo, top or reset, prints top() for each top and finally players: with the count.
Your code goes in Leaderboard.kt and Functions.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()
for (cmd in input) {
val p = cmd.split(" ")
when (p[0]) {
"win" -> recordWin(p[1])
"draw" -> recordDraw(p[1], p[2])
"reset" -> Leaderboard.reset()
else -> println(Leaderboard.top())
}
}
println("players: ${Leaderboard.players}")
}
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 Books3Objects and Companions
Object DeclarationsCompanion ObjectsConstants With constObject ExpressionsRecap - Ticket OfficePractice on your own: Kotlin playground