Search⌘ K
AI Features

Data Classes and the Any Class

Explore how Kotlin's Any class serves as the base for all types, providing essential methods like equals, hashCode, and toString. Learn how data classes use these methods automatically to manage data objects efficiently, offering built-in copying and component functions.

Use of the Any class

If a class has no explicit parent, its implicit parent is Any, which is a superclass of all the classes in Kotlin. This means that when we expect the Any? type parameter, we accept all possible objects as arguments.

Kotlin 1.5
fun consumeAnything(a: Any?) {
println("Om nom $a")
}
fun main() {
consumeAnything(null) // Om nom null
consumeAnything(123) // Om nom 123
consumeAnything("ABC") // Om nom ABC
}

We can think of Any as an open class with three methods:

  • toString

  • equals

  • hashCode

Tip: Overriding methods defined by Any is optional because each is an open function with a default body.

Understanding the Any superclass

In Kotlin, we say ...