Introduction
In Kotlin, Any is the base type for all other types. It lets you store any kind of value in one place.
In Kotlin, Any is the base type for all other types. It lets you store any kind of value in one place.
val variableName: Any = valueYou can assign any value to a variable of type Any.
To use specific features of the stored value, you may need to check its type first.
Any can hold different types of values.val number: Any = 42 val text: Any = "Hello" val flag: Any = true
Any.fun printAny(value: Any) { println(value) }
Any.val mixedList: List<Any> = listOf(1, "two", 3.0, false)
This program shows how Any can hold different types of values and how to print them.
fun main() { val data: Any = "Kotlin" println(data) val number: Any = 123 println(number) val mixedList: List<Any> = listOf("apple", 10, 3.14, true) for (item in mixedList) { println(item) } }
Any is like the root of all types in Kotlin.
To use specific properties or methods of the stored value, use type checks like is or casts.
Any can hold any type of value.
Useful for flexible variables and collections.
Type checks help when you want to work with the actual type inside Any.
Any as the root of its type system, similar to Object in Java.Any can hold any non-null value, making it the universal base type in Kotlin.Any in Kotlin?val or var, followed by a colon and the type.Any typeAny is a type, not a constructor, so you assign values directly without parentheses.val x: Any = 10 [OK]fun main() {
val a: Any = "Hello"
val b: Any = 123
println(a)
println(b)
}a holds a string "Hello" and b holds an integer 123, both typed as Any.a and b calls their toString() method, outputting "Hello" and "123" respectively.fun main() {
val x: Any = null
println(x)
}Any in Kotlin is non-nullable by default, so it cannot hold null.null to x of type Any causes a compile-time error.Any as the base type?val mixedList: List<Any> = listOf(1, "two", 3.0, true)
List<String> with string forms of all elements?val stringList = mixedList.map { it.toString() } maps each element to its string form, producing List<String>. val stringList = mixedList.filterIsInstance<String>() filters only strings, losing other elements. val stringList = mixedList.map { it as String } tries unsafe cast causing runtime error. val stringList = mixedList.filter { it is String } filters strings but returns List<Any>, not List<String>.Pass the test and this pattern moves unknown