To create single, unnamed instances of a class, Kotlin introduces the notion of object expressions. To create an object expression, we use the object keyword followed by : and then any class or interface names we want to use:
val someInterface = object : SomeInterface {
override fun doSomething(foo: String) {
super.doSomething(foo)
}
}
Object declarations can implement multiple interfaces and have access to the variables defined within the scope in which they were created. It's also possible to use an object expression to create an unnamed class with no supertype. In this example, we assign an object expression to transient, in which we've declared a single property:
fun main(args: Array<String>) {
val transient = object {
val prop = "foo"
}
println(transient.prop)
}
That property can then be used within the same scope in which transient is available.
One key difference between object expressions and object declarations is that object declarations are instantiated lazily upon first use, whereas object expressions are created and used immediately.
In this section, we've introduced and explored several special types of classes that add to Kotlin's rich typing system. Enums, sealed classes, companion objects, and object expressions all serve specific use cases and can enable developers to write more expressive, safer code with less boilerplate.