What are Object expressions in Kotlin and when to use them?

Technology CommunityCategory: KotlinWhat are Object expressions in Kotlin and when to use them?
VietMX Staff asked 3 years ago

Sometimes we need to create an object of some class with slight modification, without explicitly declaring a new subclass for it. Java handles this case with anonymous inner classes. Kotlin uses object expression to achieve the same functionality. We can even create an object expression for an interface or abstract class by just implementing their abstract methods.

It is often used as a substitution to a Java anonymous class:

window.addMouseListener(object : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) {
        // ...
    }

    override fun mouseEntered(e: MouseEvent) {
        // ...
    }
})