Junior — Middle
Can you explain the difference between the Object class in Java and the Any type in Kotlin?
sobes.tech AI
Answer from AI
In Java, the Object class is the base class for all classes, from which all objects inherit. It defines basic methods such as toString(), equals(), hashCode(), and others.
In Kotlin, the Any type is analogous to Object in Java, serving as the base type for all non-nullable types. However, Any does not have methods related to null, and it does not include methods that Object has for working with null.
Key differences:
Anycannot be null; for that, there is a separate typeAny?.- Methods in
Anyare limited: there areequals(),hashCode(), andtoString(), but no methods related to synchronization or cloning, which are present inObject. - Kotlin does not have a direct equivalent of
finalize()fromObject.
Example:
val a: Any = "Hello"
val b: Any? = null // nullable Any
Thus, Any is a cleaner and safer base type without null support, unlike Object in Java.