0
0
Kotlinprogramming~5 mins

Any type as universal base in Kotlin

Choose your learning style9 modes available
Introduction

In Kotlin, Any is the base type for all other types. It lets you store any kind of value in one place.

When you want a variable to hold any kind of data, like numbers, text, or objects.
When you write functions that can accept any type of input.
When you need to store mixed types in a collection like a list or array.
When you want to write generic code without specifying exact types.
Syntax
Kotlin
val variableName: Any = value

You 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.

Examples
Variables of type Any can hold different types of values.
Kotlin
val number: Any = 42
val text: Any = "Hello"
val flag: Any = true
A function that accepts any type of value using Any.
Kotlin
fun printAny(value: Any) {
    println(value)
}
A list holding different types because its elements are of type Any.
Kotlin
val mixedList: List<Any> = listOf(1, "two", 3.0, false)
Sample Program

This program shows how Any can hold different types of values and how to print them.

Kotlin
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)
    }
}
OutputSuccess
Important Notes

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.

Summary

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.