liveBook · Manning

Object expression

As explained in Kotlin in Action, 2E

An object expression is Kotlin syntax that creates an anonymous object, optionally implementing a class or interfaces, at the point where it is written.

An object expression creates an anonymous object at the point where it is written. It can implement one or more interfaces, extend a class, or stand alone, making it Kotlin’s concise replacement for Java anonymous inner classes. section 4.4.4 section 4.6

Create an event listener inline

Button(object : MouseListener { override fun onEnter() { /* ... */ } override fun onClick() { /* ... */ } }) The object expression declares an unnamed class and immediately creates its instance. Omitting a name distinguishes it from an object declaration. Each execution creates a new instance, rather than reusing a singleton. section 4.4.4

Use an object expression when the implementation needs a compact, local object:

  • Implement multiple interfaces or provide several overridden methods in one local definition. section 4.4.4 section 4.6
  • Capture local variables from the surrounding function; unlike Java’s restriction, Kotlin also permits modifying them. section 4.4.4
  • Prefer a lambda or SAM conversion for a single-method interface when an object instance is unnecessary. section 4.4.4

Capture mutable state

var clickCount = 0 Button(object : MouseListener { override fun onEnter() { /* ... */ } override fun onClick() { clickCount++ } }) The listener can update the surrounding function’s local variable, which is useful for small pieces of event-handling state.

An anonymous object has its own this reference, unlike a lambda. That makes it appropriate when a listener must refer to itself, such as unsubscribing from an event source while handling an event. section 5.2.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains syntax, instance creation, interface combinations, variable capture, mutation, and the boundary with SAM conversion.
Examples
Uses MouseListener event handling, stored listeners, and a mutable click counter as concrete examples.
What it assumes
Assumes interfaces and Java anonymous inner classes while demonstrating Kotlin syntax from inline listener construction.
What you can do after
Apply it to implement multi-method listeners, capture local state, and choose between anonymous objects and lambdas.
How it connects
Connects object expressions with object declarations, interfaces, anonymous inner classes, lambdas, and SAM conversion.

Also explained in

Compare how 2 books explain object expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.