0
0
Kotlinprogramming~5 mins

Object expressions (anonymous objects) in Kotlin

Choose your learning style9 modes available
Introduction

Object expressions let you create objects quickly without making a new class. They are useful when you need a simple object just once.

When you want to handle a button click with a quick action in Android.
When you need a small helper object for one-time use.
When you want to override a method for a specific case without creating a full class.
When you want to group some data and behavior temporarily.
When you want to implement an interface or abstract class on the spot.
Syntax
Kotlin
val obj = object {
    val property = value
    fun method() {
        // code
    }
}

The object keyword creates an anonymous object.

You can define properties and functions inside it.

Examples
This creates an object with a greeting and a function to print it.
Kotlin
val obj = object {
    val greeting = "Hello"
    fun sayHello() = println(greeting)
}
obj.sayHello()
This creates an anonymous object implementing the ClickListener interface.
Kotlin
interface ClickListener {
    fun onClick()
}

val listener = object : ClickListener {
    override fun onClick() {
        println("Clicked!")
    }
}
listener.onClick()
Sample Program

This program creates an anonymous object representing a person with a name and a greeting method. It then prints the greeting.

Kotlin
fun main() {
    val person = object {
        val name = "Alice"
        fun greet() = "Hi, I am $name"
    }
    println(person.greet())
}
OutputSuccess
Important Notes

Anonymous objects are useful for quick, one-time use without cluttering your code with many classes.

If you assign an anonymous object to a variable with an explicit type, only the declared type's members are accessible.

Anonymous objects can implement interfaces or extend classes.

Summary

Object expressions create quick, unnamed objects.

They help you write less code for simple tasks.

You can add properties and functions inside them.