Search⌘ K

Data Classes and the Any Class

Explore Kotlin’s Any superclass, customize object behaviors, and optimize modeling with data classes.

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 ...