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 1A 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 formChallenge
EasyThe 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("; "))
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing Books3Objects and Companions
Object DeclarationsCompanion ObjectsConstants With constObject ExpressionsRecap - Ticket OfficePractice on your own: Kotlin playground