Summary - Object declaration
- Kotlin course
- Intermediate
- Lesson 35/116
- 5 min
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.
Practice 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()).
Starter code
// Define the Logger object and App class
// a class-level singleton block with a create factory method
// start method calls Logger
// start in main and print the resultSample 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())
}Expected output
[LOG] started
Practice 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")).
Starter code
// Define the Formatter interface
// implement it with an anonymous object in main
// call format and printSample solution
interface Formatter {
fun format(message: String): String
}
fun main() {
val f = object : Formatter {
override fun format(message: String) = ">> $message"
}
println(f.format("test"))
}Expected output
>> test
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which structure suits logging for an application?
- A new class each time
- A local variable
- An abstract interface
- object Logger (singleton) Correct answer
Explanation: object Logger keeps a single instance for logging across the app.
2 Complete the companion + Logger call
class App {
____ object {
fun create(): App = App()
}
fun start(): String = Logger.log("started")
}
class App {
companion object {
fun create(): App = App()
}
fun start(): String = Logger.log("started")
}
Explanation: companion object declares a class-level singleton.