CodeBlanks Logo Icon CodeBlanks

Object expression

Learn to create anonymous objects with object:.

object expression

An object expression is an anonymous object that implements an interface or class without giving it a name. It is written as object : Type { ... }. It is convenient for one-off implementations.

Example: val listener = object : ClickListener { override fun onClick() = "clicked" }. Here an unnamed object implementing ClickListener is created. It is assigned to a variable and used later. It provides a quick implementation without a class definition; similar to anonymous inner classes in Java.

The ClickListener interface

An object expression is most often used to implement an interface. All methods of the interface must be overridden.

Example: interface ClickListener { fun onClick(): String }. To implement it: val l = object : ClickListener { override fun onClick() = "clicked" }. Calling l.onClick() returns clicked. An object expression gives a one-off implementation without opening a new class file. If the interface has multiple methods, you must override all of them.

Practice An anonymous object implementing ClickListener

Define an interface ClickListener with a fun onClick(): String method. In main create an anonymous object as val listener = object : ClickListener { override fun onClick() = "clicked" } and print the result with println(listener.onClick()).

Starter code

Main.kt
// Define the ClickListener interface
// implement it with an anonymous object in main
// call onClick and print

Sample solution

Main.kt
interface ClickListener {
    fun onClick(): String
}

fun main() {
    val listener = object : ClickListener {
        override fun onClick() = "clicked"
    }
    println(listener.onClick())
}

Expected output

clicked

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the object expression

Question
val listener = ____ : ClickListener {
    override fun onClick() = "clicked"
}
Answer
val listener = object : ClickListener {
    override fun onClick() = "clicked"
}

Explanation: object : Type creates an anonymous object.

2 Match the object expression parts

Term Meaning
object : ClickListener Anonymous object
override fun onClick Method implementation
val l = object Assignment
"clicked" Return value

3 When is an <strong>object expression</strong> preferred?

  • When a one-off anonymous implementation is needed Correct answer
  • When you need to create multiple instances
  • When you want to open a new class file
  • When you want to open an abstract class

Explanation: An object expression provides a one-off anonymous implementation.

All lessons in Intermediate