Kotlin - Void vs. Unit vs. Nothing

Matthew Layton picture Matthew Layton · May 2, 2019 · Viewed 26.5k times · Source

Kotlin has three types that are very similar in nature:

  • Void
  • Unit
  • Nothing

It almost seems like they're making the JavaScript mistake:

  • null
  • undefined
  • void(0)

Assuming that they haven't fallen into the same mistake, what are they all for, and how do they differ?

Answer

marstran picture marstran · May 2, 2019

The Void type is from Java. You generally won't use this from Kotlin unless you're using some Java-library that uses it.

The Unit type is what you return from a function that doesn't return anything of interest. Such a function is usually performing some kind of side effect. The unit type has only one possible value, which is the Unit object. You use Unit as a return type in Kotlin when you would use void (lowercase v) in Java.

The Nothing type has no values. If a function has return type Nothing, then it cannot return normally. It either has to throw an exception, or enter an infinite loop. Code that follows a call to a function with return type Nothing will be marked as unreachable by the Kotlin compiler.

Because Nothing has no values, Nothing? is actually the type that captures only the null value in Kotlin.