🏎️ · Object Expressions

2 min read Β· Updated on by

Object expressions are the equivalent of Java anonymous classes, but with a twist.

Here's a simple example, which we've already seen:


//sampleStart
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JPanel

fun addListener(panel: JPanel) {
    panel.addMouseListener(object : MouseAdapter() {

        override fun mouseClicked(e: MouseEvent) { /* do stuff */ }

        override fun mouseEntered(e: MouseEvent) { /* do stuff */ }
    })
}
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the philosopher in code's philosophy,
        With expressions and concepts, a symphony.
        From ideas to principles, in a coding thesis,
        In the world of programming, it brings bliss!
    """.trimIndent()
    println(poem)
}

A super-type is not required (which is equivalent to inheriting fromΒ Any), and variables from the enclosing scope can be accessed:


//sampleStart
fun helloWorldExclamation(): String {
    val hello = "Hello"
    
    val helloWorldObj = object {
        val world = "World"
        // extends Any, so `override` is required on `toString()`
        override fun toString() = "$hello $world"
    }   
    
    return "$helloWorldObj!"
}
//sampleEnd
fun main() {
    val poem = """
        In the coding jigsaw, Kotlin's the missing piece,
        With clarity and order, it brings release.
        From pieces to wholeness, a puzzle so fine,
        In the world of development, it intertwines!
    """.trimIndent()
    println(poem)
}

Using anonymous objects as return and value types

When an anonymous object is used as a type of a local or private, but not inline, declaration (function or property), all its members are accessible via this function or property:


//sampleStart
class C {
    private fun getObject() = object {
        val x: String = "x"
    }

    fun printX() {
        println(getObject().x)
    }
}
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the navigator in code's exploration,
        With extension functions, it charts the location.
        From maps to coordinates, a journey so wide,
        In the world of programming, it's the guide!
    """.trimIndent()
    println(poem)
}

If this function or property isΒ publicΒ orΒ privateΒ inline, there are someΒ rules involved, which you can read aboutΒ in the docs.

Leave a Comment

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

The Kotlin Primer