CodeBlanks Logo Icon CodeBlanks

Any and Unit

Learn Any and Unit types.

Any and Unit

Any is the supertype of all non-nullable types in Kotlin. If a variable can hold values of different types, you can use Any: val x: Any = 5 then x = "text" is valid.

Unit indicates that a function returns no value; it is Kotlin's equivalent of Java's void but is actually a type with a single instance.

fun hello(): Unit {
    println("Hello")
}

Practice Unit function

At the top level, write fun hello(): Unit with a println("Hello") inside. Inside fun main(), call hello().

Sample solution

Main.kt
fun hello(): Unit {
    println("Hello")
}

fun main() {
    hello()
}

Expected output

Hello

The Nothing type

Nothing is Kotlin's bottom type: it represents computations that never complete. For example, an infinite loop or a function that always throws returns Nothing.

In practice, the TODO() function returns Nothing; this makes it useful to mark code not yet written. Don't confuse it with Unit: Unit does return a value (its single instance), Nothing never returns.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Return type

Question
fun hello(): ____ {
    println("Hello")
}
Answer
fun hello(): Unit {
    println("Hello")
}

Explanation: Unit is the type of a function that returns no value.

2 Of which types is Any the supertype?

  • All non-nullable types Correct answer
  • Only Int
  • Only String
  • Only classes

Explanation: Any is the supertype of all non-nullable types.

3 Any and Unit: match the terms

Term Meaning
Any Supertype
Unit No return
Nothing Never returns
Int Integer

All lessons in Beginner