Junior — Middle
What is the purpose of the Any type in Kotlin and when is it used?
sobes.tech AI
Answer from AI
In Kotlin, the Any type is the superclass of all types, similar to Object in Java. It represents the most general type to which any object can be cast.
The purpose of Any is to serve as a base type when working with objects of unknown or arbitrary types.
Any is used in cases where:
- You need to store or pass values of different types in a single structure.
- Define functions or variables that can accept or return any object.
Example:
fun printAny(value: Any) {
println(value.toString())
}
printAny(123) // outputs 123
printAny("text") // outputs text
It is important to remember that Any only has basic methods (toString(), equals(), hashCode()), so to work with specific properties or methods, you need to cast the type to a more specific one.