Menu
Coddy logo textTech

Object Expressions

Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 15 of 57.

An object expression creates a one-off object of an unnamed class, right where it is needed. It is written object : Type { ... } and usually implements an interface. An interface lists methods without saying how they work; chapter 5 covers interfaces in depth:

interface Greeter {
    fun greet(name: String): String
}

Inside main:

val polite = object : Greeter {
    override fun greet(name: String) = "Good morning, $name."
}
println(polite.greet("Ada"))

Output:

Good morning, Ada.

An object declaration exists once. An object expression is evaluated every time its code runs, and each run creates a new object. It can read and change the local variables around it:

interface Counter {
    fun next(): Int
}

fun counterFrom(start: Int): Counter {
    var current = start
    return object : Counter {
        override fun next() = current++
    }
}

Inside main:

val a = counterFrom(10)
val b = counterFrom(1)
println("${a.next()} ${a.next()} ${b.next()}")

Output:

10 11 1

A common use is handing behaviour to a library function. sortedWith takes a Comparator, an interface whose method compare(a, b) returns a negative number when a comes first, zero for a tie and a positive number otherwise:

Inside main:

val words = listOf("kiwi", "fig", "banana", "apple")
val byLength = object : Comparator<String> {
    override fun compare(a: String, b: String) = a.length - b.length
}
println(words.sortedWith(byLength))

Output:

[fig, kiwi, apple, banana]

An object expression without a supertype groups a few values into a local object; its properties can be used inside the same function. When an interface has a single method, a lambda is often shorter than an object expression. Object expressions fit when there are several methods or some state to keep.

val size = object {
    val width = 3
    val height = 4
}
println(size.width * size.height)                    // 12

val byLength = Comparator<String> { a, b -> a.length - b.length }   // lambda form
challenge icon

Challenge

Easy

The interface Validator has one method, check(text), which returns an error message or null when the text passes. Complete the function rules(minLength) so it returns three validators created with object expressions, in this order: the text must have at least minLength characters (too short), contain a digit (needs a digit) and contain no spaces (no spaces allowed).

The supplied code reads the minimum length and then one password per line. It prints ok, or every error message of that password joined with ; .

Your code goes in Rules.kt and Validator.kt. Main.kt holds the supplied input/output code and cannot be edited.

Try it yourself

fun main() {
    // Supplied input/output code: keep it as it is
    val input = generateSequence(::readLine).toList()
    val checks = rules(input[0].toInt())
    for (password in input.drop(1)) {
        val problems = checks.mapNotNull { it.check(password) }
        println(if (problems.isEmpty()) "ok" else problems.joinToString("; "))
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Kotlin playground