Anonymous Objects
Inline implementations.
Inline Implementations
An anonymous object creates an instance of a class or interface without naming a new class. Use the object expression.
interface Greeter { fun greet(): String }
fun main() {
val g = object : Greeter {
override fun greet() = "Hi"
}
println(g.greet())
}Implementing an Interface
An object expression can implement one or more interfaces right where it is needed.
interface Clickable { fun click() }
fun main() {
val button = object : Clickable {
override fun click() = println("Clicked")
}
button.click()
}All lessons in this course
- Nested Classes
- Inner Classes
- Anonymous Objects
- Local Classes