Sobes.tech
Junior — Middle

How do Java Object types differ from Kotlin's Any in terms of purpose and usage?

sobes.tech AI

Answer from AI

In Java, the Object type is the base class for all classes, from which all objects inherit. It is used to represent any object but cannot directly contain primitive types.

In Kotlin, the type Any is analogous to Object, serving as the base type for all classes. However, unlike Java, Kotlin separates Any and Any? (nullable). Any cannot contain null, but Any? can. Additionally, Kotlin has separate types for primitives, which are automatically converted to objects when necessary.

Example:

fun printAny(value: Any) {
    println(value.toString())
}

printAny(123)       // Int is automatically converted to Any
printAny("text")   // String is a subclass of Any

Thus, Object in Java is a class, whereas Any in Kotlin is a base type that does not allow null, enhancing type safety.

How do Java Object types differ from Kotlin's Any in… - sobes.tech