Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære The Any Type | Nullable and Special Types
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
Kotlin Data Types

bookThe Any Type

Sveip for å vise menyen

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

Main.kt

copy
12345678910111213
package 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.

question mark

What is the purpose of the Any type in Kotlin?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 3
some-alt