Object expressions in kotlin

Mangesh Yadav
2 min readApr 26, 2022

What are Object expressions?

Object expressions create objects of anonymous classes, that is, classes that aren’t explicitly declared with the class declaration. Such classes are useful for one-time use. You can define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by an expression, not a name.

Creating anonymous objects

anonymous objects are created using the object keyword.

val user = object {
val firstName = "John"
val lastName = "Dev"
// object expressions extend Any, so `override` is required on `toString()`
override fun toString() = "$firstName $lastName"
}

members of the anonymous object can be accessed using . dot operator.

Anonymous objects as return and value type

an anonymous object can be used as a return type of a function. To access the members of the object the function should be local or private (but not inline).

private fun user() = object {
val firstName = "John"
val lastName = "Dev"
// object expressions extend Any, so `override` is required on `toString()`
override fun toString() = "$firstName $lastName"
}

If this function or property is public or private inline, The return type becomes

  • Any if the function doesn’t have a declared supertype.
  • The declared supertype if there is only one.
  • The explicitly declared type if there is more than one supertype.
class Demo{
// The return type is Any. firstName is not accessible
fun getName() = object {
val firstName:String = "John"
}

// The return type is User. firstName is not accessible
fun getUser() = object : User{
override fun getId() {}
val firstName:String = "John"
}

// The return type is Address; getId() and firstName are not
accessible
fun getAddress():Address = object : User, Address{
// explicit return type is required
override fun getId() {}
val firstName:String = "John"
}
}

Check another story on Companion Object vs Package-Level Function in Kotlin.

https://mangeshyadav786.medium.com/companion-object-vs-package-level-function-4b00eae712dc

--

--