Sobes.tech
Junior — Middle

How can the capabilities of the Any class be extended?

sobes.tech AI

Answer from AI

The Any class in Android (for example, in Kotlin) is a universal container for storing a value of any type. Its capabilities can be extended in the following ways:

  • Extension functions: add extension functions for convenient extraction or transformation of the stored value.

  • Wrappers and utilities: create helper classes or methods for safe and convenient access to the contents of Any.

  • Using sealed classes or generics: for more strict typing and handling of various content options.

Example of an extension function for safe casting of Any to the desired type:

inline fun <reified T> Any?.safeCast(): T? = this as? T

val value: Any = "Hello"
val str: String? = value.safeCast<String>() // str will be "Hello"
val num: Int? = value.safeCast<Int>() // num will be null