Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 134 ยท Control Flow

Any, Unit and Nothing

Learn Kotlin's top and bottom types - Any, Unit and Nothing - plus TODO(), error(), require() and check(), with runnable examples and the real compiler messages.

Most languages have a few special types that are not about numbers or text but about the shape of the type system itself. Kotlin has three of them, and they have short, odd-looking names: Any, Unit and Nothing. They answer three questions. What type can hold any value? What type does a function return when it has nothing interesting to say? And what type does an expression have when it never finishes at all?

Once you understand these three, many things that look like special cases in Kotlin stop being special: why if can be used as an expression with a throw in one branch, why a function without a return value still "returns" something, and why TODO() and error() fit anywhere you put them. This lesson walks through each type, then looks at the four standard functions that make failing early a habit: TODO(), error(), require() and check().

Any: the top of the type hierarchy

Every non-nullable type in Kotlin is a subtype of Any. An Int is an Any, a String is an Any, and so is every class you write. That makes Any the right type for a variable that must accept anything, and it is the Kotlin counterpart of Java's Object.

Any itself only promises three members: equals(), hashCode() and toString(). Everything else you must earn by checking what the value really is, using is (see Type Checks and Casts).

Kotlin Any holds everything, but promises little

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Inside the first branch, value is smart-cast to Int, so value * 2 compiles. Outside a check, a variable of type Any knows nothing about its contents, so the compiler refuses anything that is not on Any itself.

Kotlin No arithmetic on Any (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:3:15: error: unresolved reference 'plus' for operator '+' on receiver of type 'Any'. The value really is the number 5, but the type Any has no plus. Check with is Int first, or give the variable a more precise type.

Any? and the nullable top

Any does not include null. The real top of the whole hierarchy is Any?, the nullable version. Use Any? when null is a legal input too, for example a function that prints any value including a missing one:

Kotlin
fun show(value: Any?) = println(value ?: "nothing here")

This distinction matters for null safety: val x: Any = null does not compile, but val x: Any? = null does.

Prefer a precise type or a generic over Any. Every time you use Any, the compiler stops helping you and you must write is checks by hand. Real code uses Any mostly for things like equals(other: Any?), logging, and heterogeneous containers.

Unit: a function that returns "nothing interesting"

In many languages a function that returns no value is a special case with a keyword like void. In Kotlin, every function returns a value of some type, and a function with nothing useful to return gives back Unit. Unit is an ordinary type that has exactly one value, also called Unit.

You never have to write it. These two functions are identical:

Kotlin Unit is the default return type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The two println(a) and println(b) lines print kotlin.Unit, which is how the single Unit value shows itself as text. Both variables hold the same value, so a == b is true. In practice you almost never capture a Unit; the point is that you can.

Why having a real Unit type helps

Because Unit is a proper type, it fits everywhere a type is expected. That matters most with generics and lambdas: List<Unit> is legal, and a function type such as (String) -> Unit is simply "takes a string and returns nothing useful". If Kotlin used a magic void, every generic API would need a second, void-friendly version. Compare how Java needs both Function and Consumer. The function types lesson builds on this.

Kotlin Unit as a generic type argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The same runAndReport handles an action that returns an Int and an action that returns Unit. For the second call the lambda's last expression is println(...), whose type is Unit, so T becomes Unit and the report line prints kotlin.Unit.

A function that returns Unit can also use a short body such as fun log(m: String) = println(m), because println returns Unit. Be careful with one thing: a block body that should return something but does not is an error, not a Unit return. If you write fun total(): Int { ... } you must return an Int.

Nothing: the type that never finishes

Nothing is the opposite of Any. It sits at the bottom of the hierarchy: it is a subtype of every other type, and it has no values at all. An expression of type Nothing never produces a result, because it never completes normally. Instead it throws, loops forever, or ends the program.

The most familiar Nothing expression is throw:

Kotlin throw has type Nothing (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at ?: throw .... The Elvis operator needs both sides to fit into one type. The left side is Int?. The right side is throw, which is Nothing. Since Nothing is a subtype of every type, it fits as an Int without any conversion, and the whole expression has type Int. That is the same reason else throw ... is fine in the val label: String line.

The last call fails with an unhandled exception: Exception in thread "main" java.lang.IllegalArgumentException: not a number: eighty followed by a stack trace.

Functions that return Nothing

You can declare your own function with the return type Nothing when it can never return normally. The compiler then knows that code after the call is unreachable, and uses that fact for smart casts:

Kotlin A helper that returns Nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After raw ?: fail(...), the compiler knows that text is a non-null String, because the only other path never comes back. A declared Nothing function must really never return. If you forget the throw, the compiler tells you:

Kotlin A Nothing function that returns (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is main.kt:3:1: error: missing return statement. pointing at the closing brace: the compiler found a way to reach the end of a function that promised not to.

Nothing and the empty collection

Nothing also shows up when the compiler has no information to infer a type from. val x = null has type Nothing?, and listOf() with no elements and no expected type cannot work out its element type. When there is an expected type, as in val names: List<String> = emptyList(), inference fills it in. That is also why emptyList<Nothing>() is a subtype of List<String> and List<Int> alike: a list that holds no values of the bottom type can safely be viewed as a list of anything. Variance explains why.

TODO(), error(), require() and check()

The standard library gives you four small functions built on Nothing or on exceptions. They turn "this must hold" into running code.

Function Throws Use it for
TODO() NotImplementedError Code you have not written yet
error(msg) IllegalStateException A state that should be impossible
require(cond) { msg } IllegalArgumentException Checking arguments passed in by the caller
check(cond) { msg } IllegalStateException Checking the object's own state

TODO() and error() both return Nothing, so they type-check anywhere. That makes TODO() ideal for sketching: your program compiles, and only fails if that path actually runs.

Kotlin TODO and error as placeholders (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The HIGH branch is typed Nothing, so it fits the Int result of the when. The first two calls print 1 and 5. The third throws NotImplementedError with the message An operation is not implemented: price the high tier, which the catch prints. Then error("cannot continue") throws IllegalStateException, so the last println(value) never runs and the program ends with an unhandled exception.

require versus check

Both functions test a condition and throw if it is false. The difference is whose fault it is.

  • Use require at the top of a function to validate arguments. A failure means the caller passed bad input, and it throws IllegalArgumentException.
  • Use check to validate state: things that must be true about the object or the program at that moment. A failure means a bug or a wrong call order, and it throws IllegalStateException.
Kotlin require for arguments, check for state (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first call prints withdrew 30, balance is now 70. The attempt of -5 triggers require, so it is reported as a bad argument. The attempt of 500 passes require but fails the balance check, so it is reported as a bad state (insufficient funds: 70 < 500). The final call after close() is not caught, and ends the program with IllegalStateException: account is closed.

The lambda after each call, { "..." }, builds the message lazily: it only runs if the condition fails, so a failing check pays for string building and a passing one costs nothing.

There is one more benefit. After require(x != null) or check(x != null), the compiler smart-casts x to non-null for the rest of the function, because the condition is known to be true if execution continues. The related requireNotNull and checkNotNull functions return the non-null value directly, and require, check and assert get a lesson of their own later.

assert(condition) is the third sibling, but it does nothing unless the JVM runs with -ea. Do not rely on it for validation that must always happen. Use require or check.

Putting the three types together

A quick way to remember the roles:

  • Any is the ceiling: it can hold any non-null value, so it can be assigned from anything.
  • Nothing is the floor: it can be assigned to anything, because it never produces a value.
  • Unit sits in the middle as an ordinary type with exactly one value, used when there is nothing meaningful to return.

When you read a function signature, : Unit (or no return type) tells you it is called for its effects, : Nothing tells you it never comes back, and : Any tells you almost nothing, which is usually a sign to look for a better type.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type is a supertype of every non-nullable Kotlin type?

    Any is the root of the non-nullable hierarchy. Nothing is the opposite (a subtype of everything), Unit is an ordinary one-value type, and Object is Java's name for a similar idea.
  2. 2. What does a function without a declared return type and without a return statement give back?

    Such a function returns Unit, the type with exactly one value. Printing that value gives kotlin.Unit.
  3. 3. Why does val n: Int = text.toIntOrNull() ?: throw IllegalArgumentException() compile?

    throw is an expression of type Nothing. Because Nothing is a subtype of every type, it fits where an Int is expected, and the whole expression is an Int.
  4. 4. A caller passes a negative amount to your function. Which check fits best?

    require validates arguments and throws IllegalArgumentException. check is for the object's own state.
  5. 5. What does a declared : Nothing function promise?

    A Nothing function always throws, loops forever or ends the program. The compiler uses this to treat code after the call as unreachable and to smart-cast values.

Summary

  • Any is the root of all non-nullable types; Any? is the root including null. It only guarantees equals, hashCode and toString.
  • Functions with no useful result return Unit, a real type with one value that works inside generics and function types.
  • Nothing is a subtype of every type with no values; throw, TODO() and error() have this type, which is why they fit in any expression.
  • A function declared : Nothing must never return normally, and the compiler reports missing return statement if it can.
  • require checks arguments (IllegalArgumentException), check checks state (IllegalStateException), and both build their message lazily.

Next: Functions