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
- object Declaration: Kotlin Singletons
- companion object: Static-like Members in Kotlin
- Anonymous Objects and Object Expressions
- Factory Methods with companion object