Sobes.tech
Junior — Middle

What are the ways to implement creating anonymous class instances in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, creating anonymous instances of classes is usually done using anonymous objects. This allows you to create an object that inherits from a class or implements an interface without explicitly declaring a new class.

Example of creating an anonymous object implementing an interface:

interface ClickListener {
    fun onClick()
}

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

listener.onClick()

You can also create anonymous objects that extend a class:

open class Animal {
    open fun sound() = println("Some sound")
}

val dog = object : Animal() {
    override fun sound() = println("Woof")
}

dog.sound()

Thus, anonymous objects allow for quickly creating instances with overridden behavior without creating a separate named class.