Any

Any in Kotlin is on the top of the hierarchy. All other types descend from Any.

From the class documentation: “The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.”

It works like Java Object, but it has a much leaner signature:

public open class Any {

public open operator fun equals(other: Any?): Boolean public open fun hashCode(): Int public open fun toString(): String

}

As a comparison java.lang.Object has 11 methods, of which five are about synchronization ( wait , notify , notifyAll ).

This is clearly an example of the advantages of coming later, it might seem a good idea at the time, but now having synchronization primitives on any possible object now seems unnecessary. There is also a reference on Valhalla project mailing list about it.

Looking at the code for Any , we can also see that is one of the few classes in the Kotlin stdlib that is open, meaning that is possible to inherit directly from it. This is necessary because every Kotlin class automatically inherits from Any, even if you don’t have to write it explicitly, you may do.

class MyClass: Any() {

fun bye(): String = "bye bye"

}

Under the hood, at the JVM level, the Any type doesn’t exist and it gets compiled to java.lang.Object

For example:

fun whatIcanDoWithAny(obj: Any){

obj.toString()

}

Generate this bytecode where even if you are not familiar with the format. You can easily spot the actual type of the parameter (in bold).

Ljava/lang/Object;)V

// annotable parameter count: 1 (visible)

// annotable parameter count: 1 (invisible)



L0

ALOAD 0

LDC "obj"

INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V

L1

LINENUMBER 5 L1

ALOAD 0

INVOKEVIRTUAL java/lang/Object.toString ()Ljava/lang/String;

POP public final static whatIcanDoWithAny(;)V// annotable parameter count: 1 (visible)// annotable parameter count: 1 (invisible) @Lorg/jetbrains /annotations/NotNull;() // invisible, parameter 0L0ALOAD 0LDC "obj"INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)VL1LINENUMBER 5 L1ALOAD 0INVOKEVIRTUAL java/lang/Object.toString ()Ljava/lang/String;POP

Even if they are not easily accessible from Kotlin, all Kotlin objects do have all the methods missing in Any , like notify , wait , etc.

This also makes possible to pass any Kotlin object to a Java method which is expecting an Object.