Kotlin
Summary - Object declaration
Combine object, companion object and object expression to write a helper object.
Summary - Object declaration
In this group you learned object, companion object and object expression. An object declares a singleton; a companion object gives a class-level singleton; an object expression makes an anonymous implementation.
In this summary you will combine all of them into an application bootstrap. object Logger handles logs, class App is the application instance and companion object provides a factory method. Calling App.create().start() logs through Logger. When all parts come together, singleton, class and factory work side by side.
Exercise Combine Logger and App
Define an object named Logger with fun log(message: String): String returning "[LOG] $message". Define a class App with a companion object holding fun create(): App = App(). The App class has fun start(): String that returns Logger.log("started"). In main call println(App.create().start()).
Show example solution
object Logger {
fun log(message: String): String = "[LOG] $message"
}
class App {
companion object {
fun create(): App = App()
}
fun start(): String = Logger.log("started")
}
fun main() {
println(App.create().start())
}
Exercise A log formatter with object expression
Define an interface Formatter with a fun format(message: String): String method. In main create the anonymous object val f = object : Formatter { override fun format(message: String) = ">> $message" }. Print the result with println(f.format("test")).
Show example solution
interface Formatter {
fun format(message: String): String
}
fun main() {
val f = object : Formatter {
override fun format(message: String) = ">> $message"
}
println(f.format("test"))
}
Test yourself
-
Which structure suits logging for an application?
- A new class each time
- A local variable
- An abstract interface
- object Logger (singleton)
Show answer
object Logger (singleton) — object Logger keeps a single instance for logging across the app.
-
Complete the companion + Logger call
class App {
____ object {
fun create(): App = App()
}
fun start(): String = Logger.log("started")
}
Show answer
class App {
companion object {
fun create(): App = App()
}
fun start(): String = Logger.log("started")
}
Next lesson: Extension functions