How exactly Any is being compiled?

Looking at common source of class Any, it seems there is no implementation of equals, hashCode and toString, how exactly does this work. where is the actual implementation

public open class Any {
    public open operator fun equals(other: Any?): Boolean
    public open fun hashCode(): Int
    public open fun toString(): String
}
1 Like

Short answer: it’s complicated.

(That’s a valid answer to almost any question, of course, but particularly so here!)

Slightly longer answer:

As should be obvious, the Any class isn’t compiled from that code. That just defines how it appears to other Kotlin code; it’s a sort of stub implementation.

Instead, Any is a mapped type, which is provided by the relevant platform. On the JVM, it’s mapped to java.lang.Object (which is itself partly implemented by native code, not all written in Java, as you can see from one version of its source).

So in the case of the JVM, the actual implementation is effectively split between the stub Kotlin source, parts of the Kotlin compiler, the stub Java source, and parts of the Java runtime. On other platforms, it’ll be different.

1 Like

In context of JVM, does this mean, if a class doesn’t override equals, hashCode and toString then the call to any one of them will be delegated to Object’s implementation.

1 Like

That’s right.

However, you should rely only on what’s specified in the documentation, which forms the ‘contract’; implementations can and do change (and, in the case of the JVM, there are already many implementations, which may differ in some details).

So while knowing how the implementation works can be interesting and instructive, it shouldn’t have any bearing on the code you write.

1 Like

I agree about following the contract but in my opinion knowing the implementation cant cause any harm, that is how you learn, by reading the code.
The reason why I asked this question is that Any is not even an abstract class and for some magical reason it manages to define some non-abstract functions without any body and there is no explanation in the documentation as to how this is being compiled.

I think the documentation should contain this explanation as to how this is a stub and the implementation is provided by relevant platform.

I think if the multiplatform support had existed from the beginning, then Any would probably be declared as expect. However, this feature didn’t exist back then, and what we ended up with is a special-case implementation.

1 Like