0
0
KotlinConceptBeginner · 3 min read

What is Any Type in Kotlin: Simple Explanation and Examples

In Kotlin, Any is the root type of all non-nullable types, meaning every Kotlin object inherits from Any. It is similar to Object in Java and can hold any type of value except null.
⚙️

How It Works

Think of Any as the most general container in Kotlin that can hold any kind of object, like a big box that fits anything except null. Every class you create automatically inherits from Any, so you can use it when you want to accept or store any type of value without specifying exactly what type it is.

Unlike some other languages where the root type can hold null, Kotlin separates null from Any by using Any? to represent a nullable type. This helps Kotlin keep your code safer by forcing you to handle null explicitly.

💻

Example

This example shows how you can use Any to hold different types of values in one variable and check their types at runtime.

kotlin
fun printValue(value: Any) {
    when (value) {
        is Int -> println("Integer: $value")
        is String -> println("String: $value")
        else -> println("Unknown type")
    }
}

fun main() {
    printValue(42)
    printValue("Hello")
    printValue(3.14)
}
Output
Integer: 42 String: Hello Unknown type
🎯

When to Use

Use Any when you need a variable or function parameter that can accept any type of object, but you don't want to allow null. For example, if you are writing a logging function that can print any kind of data, Any is a good choice.

However, if you expect the value might be null, use Any? instead. Also, avoid overusing Any because it removes type safety and you lose the benefits of Kotlin's strong typing.

Key Points

  • Any is the root of all non-nullable types in Kotlin.
  • It can hold any object except null.
  • Use Any? to allow null values.
  • Every Kotlin class inherits from Any by default.
  • Using Any reduces type safety, so use it carefully.

Key Takeaways

Any is the base type for all non-nullable Kotlin objects.
Use Any when you want to accept any type but not null.
Use Any? if null values are possible.
Every Kotlin class inherits from Any automatically.
Avoid overusing Any to keep type safety in your code.