Junior — Middle
Kuidas erinevad Java Object tüübid ja Kotlinis Any tüübid nende eesmärgi ja kasutamise poolest?
sobes.tech AI
Vastus AI-lt
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 equivalent to Object, the base type for all classes, but unlike Java, Kotlin distinguishes between 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 needed.
Example:
fun printAny(value: Any) {
println(value.toString())
}
printAny(123) // Int is automatically converted to Any
printAny("text") // String, which inherits from Any
Therefore, Object in Java is a class, and Any in Kotlin is a base type that does not allow null, increasing type safety.