Photo by Pixabay: https://www.pexels.com/photo/piled-brown-stones-220759/

Kotlin Any vs Java Object — What’s the difference?

Messias Junior
2 min readOct 13, 2022

--

Any and Objects are the base class for Kotlin and Java respectively, they are the bedrock of them. Given that these two languages are built on top of the Java Virtual Machine and Kotlin claims to be 100% compatible with Java, it is important to understand the relation between these two classes.

Any

Any is the base class on Kotlin. Classes without inheritance inherit from Any. This class has only 3 functions as members, all public and open :

equals(): Boolean

It is used to compare two instances and verify if these objects are equal. This method can be overridden to implement custom equality algorithms.

equals() is an operator method. It means that you can compare objects using the == operator. Under the hood, the Kotlin compiler will use this method to execute this comparison.

hashCode(): Int

It is used to identify an instance of an object by using a number. This number is usually generated by calculations using the content of the object as parameters.

This method is used by hash-based data structures to help to store the objects in the right place and make the data search/retrieval faster.

Note that sometimes, objects with different contents can have the same hashcode. This method should be used together with equals() to a more assertive result.

toString(): String

This method is used to return a String representation of the given object.

Object

The Object class is the base class for Java, which means that it is the parent of all classes. This class has the same methods as the previous one, but with some additions that can be useful in some scenarios.

getClass()

As the name suggests, returns the Class<?> from a given object.

clone()

Used together with the Cloneable interface, provides us a way to implement some logic for cloning a given object.

notify(), notifyAll() and wait()

These methods are used in a multithreading environment. The method wait() (and its overloads) tells a thread, monitoring the object, that it should be suspended until notified (or until a certain timeout for the case of wait(long) and wait(long, int)).

Calling the notify() means that the thread must be resumed and the execution should continue normally.

Note that, in the case of multiple monitors on the same object, the behavior of the notifications methods is different. notifyAll() will resume all the observer threads, however, notify() will choose randomly a thread to resume.

Runtime considerations

It’s important to keep in mind that, at runtime, Any and Object are considered the same class.

Both statements return true.

Thank you for reading until here. Feel free to drop a clap if you like this kind of detailed post.

See you next time!

--

--