CodeBlanks Logo Icon CodeBlanks

object

Learn to define singleton classes with object.

object declaration

In Kotlin an object declaration defines a singleton class with a single instance. The class definition and the instance creation happen at once; there is no new keyword. Example: object Logger { fun log(message: String) { println("Log: $message") } }. This object is called directly as Logger.log("..."). There is only one Logger instance for the whole application, which makes it suitable for global state and helper functions.

The Logger example

The body of an object declaration can hold functions and properties. You access them through the object name; no instance creation is needed.

Example: object Logger { fun log(message: String) { println("Log: $message") } }. Calling Logger.log("Started") prints Log: Started. Inside an object, this refers to the object itself; it stays the same for the whole application. It is suitable for configuration, logging and helper functions.

Practice Define the Logger object

Define an object named Logger. Add a fun log(message: String) method whose body writes println("Log: $message"). In main call Logger.log("Started").

Starter code

Main.kt
// Define the Logger object
// add a log method to print the message
// call it by object name in main

Sample solution

Main.kt
object Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}

fun main() {
    Logger.log("Started")
}

Expected output

Log: Started

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an <strong>object</strong> declaration guarantee?

  • An abstract class that cannot be instantiated
  • A new instance per call
  • A single instance (singleton) Correct answer
  • Multiple instances

Explanation: An object declares a singleton with a single instance.

2 Complete the object definition

Question
object ____ {
    fun log(message: String) {
        println("Log: $message")
    }
}
Answer
object Logger {
    fun log(message: String) {
        println("Log: $message")
    }
}

Explanation: object Logger declares a singleton.

3 Match the object parts

Term Meaning
object Logger Singleton declaration
fun log(message) Method
Logger.log(...) Call
single instance Guarantee

All lessons in Intermediate