0
0
KotlinConceptBeginner · 3 min read

What is Object Expression in Kotlin: Simple Explanation and Example

In Kotlin, an object expression creates an anonymous object on the spot without a named class. It lets you define and instantiate a class at the same time, often used to override methods or implement interfaces quickly.
⚙️

How It Works

Imagine you need a one-time helper object that does a small job, like a quick tool you borrow and then discard. Instead of creating a full class with a name, Kotlin lets you create this helper directly where you need it using an object expression.

This means you write the class and create its instance in one step. The object can have properties, methods, and even override existing ones. It’s like making a custom gadget instantly instead of ordering a full product.

This is useful when you want to customize behavior without cluttering your code with many small classes. The object created this way is anonymous, meaning it has no explicit name but can be used immediately.

💻

Example

This example shows how to create an object expression to override a method from an interface.

kotlin
interface Greeter {
    fun greet()
}

fun main() {
    val greeter = object : Greeter {
        override fun greet() {
            println("Hello from object expression!")
        }
    }
    greeter.greet()
}
Output
Hello from object expression!
🎯

When to Use

Use object expressions when you need a quick, one-off implementation of a class or interface without creating a separate named class. This is common for event listeners, callbacks, or small customizations.

For example, in Android development, you might use an object expression to handle a button click without making a full class. It keeps your code concise and focused.

Also, object expressions are handy when you want to override a method temporarily or add extra behavior in a small scope.

Key Points

  • Object expressions create anonymous objects instantly.
  • They allow overriding methods or implementing interfaces on the spot.
  • Useful for small, one-time customizations without cluttering code.
  • They are different from object declarations which create singletons with names.

Key Takeaways

Object expressions create anonymous objects without naming a class.
They are perfect for quick, one-time implementations or overrides.
Use them to keep code concise when implementing interfaces or abstract classes.
They differ from named object declarations which create singletons.
Commonly used for callbacks, listeners, and small custom behaviors.