The Any Type
Glissez pour afficher le menu
In Kotlin, the Any type serves as the root of the type hierarchy for all non-nullable types. Every class and type you create directly or indirectly inherits from Any, unless it is a nullable type or a special type like Nothing or Unit. This means that a variable of type Any can hold a value of any non-nullable type, such as numbers, strings, custom objects, and more.
You will often use Any when you want to write code that works with values of arbitrary types, such as:
- Handling collections of mixed types;
- Implementing generic algorithms;
- Accepting parameters of unknown types in functions or classes.
However, since Any does not provide any information about the specific type of value it holds, you must use type checking and casting to work with the underlying value safely.
The Any type is not nullable—if you want a variable that can hold any type including null, you should use Any? instead.
Main.kt
12345678910111213package com.example fun main() { val anyNumber: Any = 42 val anyString: Any = "Kotlin" val anyList: Any = listOf(1, 2, 3) val anyChar: Any = 'A' println("anyNumber holds: $anyNumber") println("anyString holds: $anyString") println("anyList holds: $anyList") println("anyChar holds: $anyChar") }
In the example, you see variables of type Any holding an Int, a String, a List<Int>, and a Char. This flexibility is powerful, but it also means that if you need to use the value as a specific type, you must check its type at runtime using the is operator or cast it with as. For instance, before treating an Any as a String, you should check if it actually holds a string to avoid runtime exceptions.
Type checking allows you to safely determine the actual type stored in an Any variable, while casting lets you use it as that specific type. This is essential when working with APIs or data structures that use Any to represent values of various types.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion