concept Any in category kotlin

appears as: Any
Kotlin in Action

This is an excerpt from Manning's book Kotlin in Action.

This section describes the basic types used in programs, such as Int, Boolean, and Any. Unlike Java, Kotlin doesn’t differentiate primitive types and wrappers. You’ll shortly learn why, and how it works under the hood. You’ll see the correspondence between Kotlin types and such Java types as Object and Void, as well.

Similar to how Object is the root of the class hierarchy in Java, the Any type is the supertype of all non-nullable types in Kotlin. But in Java, Object is a supertype of all reference types only, and primitive types aren’t part of the hierarchy. That means you have to use wrapper types such as java.lang.Integer to represent a primitive type value when Object is required. In Kotlin, Any is a supertype of all types, including the primitive types such as Int.

Just as in Java, assigning a value of a primitive type to a variable of type Any performs automatic boxing:

val answer: Any = 42   #1 #1 - The value 42 is boxed, because Any is a reference type.

Note that Any is a non-nullable type, so a variable of the type Any can’t hold the value null. If you need a variable that can hold any possible value in Kotlin, including null, you must use the Any? type.

Under the hood, the Any type corresponds to java.lang.Object. The Object type used in parameters and return types of Java methods is seen as Any in Kotlin. (More specifically, it’s viewed as a platform type, because its nullability is unknown.) When a Kotlin function uses Any, it’s compiled to Object in the Java bytecode.

As you saw in chapter 4, all Kotlin classes have the following three methods: toString, equals, and hashCode. These methods are inherited from Any. Other methods defined on java.lang.Object (such as wait and notify) aren’t available on Any, but you can call them if you manually cast the value to java.lang.Object.