0Pricing
Kotlin Academy · Lesson

Anonymous Objects and Object Expressions

Use object expressions to create one-off implementations of interfaces.

Object Expressions

An object expression creates an anonymous, one-off instance of a class or interface — Kotlin's equivalent of Java's anonymous inner classes, but more powerful.

Implementing an Interface Anonymously

Use object : Interface { ... } to create an inline implementation.

interface ClickListener {
    fun onClick(): String
}
fun main() {
    val listener = object : ClickListener {
        override fun onClick() = "clicked!"
    }
    println(listener.onClick())
}

All lessons in this course

  1. object Declaration: Kotlin Singletons
  2. companion object: Static-like Members in Kotlin
  3. Anonymous Objects and Object Expressions
  4. Factory Methods with companion object
← Back to Kotlin Academy