Search⌘ K
AI Features

Objects Expressions and Declarations

Explore how to create unique objects in Kotlin using object expressions and object declarations. Understand their use as anonymous types or singletons, and apply these concepts to implement patterns like event listeners or single-instance classes.

Introduction to objects

An object is an instance of a class, and one common method of creating objects is using constructors:

class A
// Using a constructor to create an object
val a = A()
Creating an instance of class A using a constructor

However, this is not the only way. In Kotlin, we can also create objects using:

  • Object expression

  • Object declaration

Object expressions

To create an empty object using an expression, we use the object keyword and braces. This syntax for creating objects is known as object expression.

val instance = object {}
Creating an empty object using an object expression
...