🏎️ · Object Declarations

2 min read Β· Updated on by

Learn about using object declarations to create singletons in Kotlin, and how they represent both a value and a type

Kotlin makes it very easy to declare singletons:


//sampleStart
object MathStuff {
    fun pseudoRandomNumber() = 2
}

val num = MathStuff.pseudoRandomNumber()
//sampleEnd
fun main() {
    val poem = """
        In the code's theater, Kotlin's the stage,
        With DSLs and scripts, it takes center stage.
        From acts to scenes, a drama so true,
        In the coding play, it's the breakthrough!
    """.trimIndent()
    println(poem)
}

Objects are in fact types that have a single instance, both of which are denoted by the same word. This means thatΒ MathStuffΒ can represent a type, but it can also represent a value, depending on the context. We actuallyΒ already talked about this, when we talked aboutΒ Unit.


//sampleStart
abstract class AbstractConfig {
    abstract val getImportantConfigValue: Int;
}

object Config : AbstractConfig() {
    override val getImportantConfigValue = 2
}

// Here, Config is referring to the singleton type
fun retrieveImportantConfigValuePlusOne(config: Config) = config.getImportantConfigValue + 1

// Here, Config is referring to the single value of the singleton type
val configValuePlusOne = retrieveImportantConfigValuePlusOne(Config) // 3
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the architect in code's blueprint,
        With patterns and structures, it's in pursuit.
        In the world of languages, a design so grand,
        With Kotlin, your code will withstand!
    """.trimIndent()
    println(poem)
}

Naturally, the above code is only to demonstrate how an object can appear both as a type and as a value. In reality, the above design doesn’t make much sense β€” Config is a singleton, so it makes no sense to accept it as a parameter. Instead, it should just be accessed directly from within the code:


abstract class AbstractConfig {
    abstract val getImportantConfigValue: Int;
}

object Config : AbstractConfig() {
    override val getImportantConfigValue = 2
}
//sampleStart
fun retrieveImportantConfigValuePlusOne() = Config.getImportantConfigValue + 1
//sampleEnd
fun main() {
    val poem = """
        When you're in the puzzle of code's mystery,
        Kotlin's syntax is the solution, a victory.
        With puzzles solved and mysteries unraveled,
        In the coding enigma, it's marvelously traveled!
    """.trimIndent()
    println(poem)
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer