Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 134 ยท Generics and Types

The Type System Tour

A guided tour of the Kotlin type system: Any? at the top, Nothing at the bottom, nullability as part of the type, platform types, intersection types and smart cast rules.

You have now met the individual pieces of Kotlin's type system: nullable types, generics, variance, Unit and Nothing. This lesson puts them on one map. A good mental model of the whole system explains many compiler messages that otherwise look arbitrary: why null is not a String, why throw can appear where an Int is expected, why a value is sometimes smart cast and sometimes not, and why a call to a Java method gives you a type you cannot write down.

We will walk from the top of the type hierarchy to the bottom, then through nullability, platform types, intersection types and the rules for smart casts. Every stop has a program you can run. Earlier lessons cover the pieces in depth: Null Safety, Type Checks and Casts, Any, Unit and Nothing and Generics.

The shape of the hierarchy

Think of all Kotlin types as a tree turned into a diamond:

TEXT
                 Any?                     <- top: every value, including null
                /    \
             Any      (nullable versions of every class, e.g. String?)
           /  |  \
   String   Int   your classes ...        <- ordinary types
           \  |  /
          Nothing?   (only value: null)
              |
           Nothing                         <- bottom: no value at all
  • Any? is the supertype of everything. A variable of type Any? can hold any value or null.
  • Any is the root of all non-null types. It declares equals, hashCode and toString.
  • Each class C has a non-null type C and a nullable type C?. C is a subtype of C?.
  • Nothing? is a subtype of every nullable type; its only value is null.
  • Nothing is a subtype of every type, and it has no values.

The following program asks the compiler questions about this tree by assigning upward. Assignments that go from a subtype to a supertype always work:

Kotlin Assigning up the hierarchy

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.

Going the other way, from supertype to subtype, always needs a check or a cast, and it is where the compiler protects you. Assigning maybeText back to a String is an error, which brings us to nullability.

Nullability is part of the type

In many languages null is a value that any reference may hold, which is the source of the famous null pointer errors. In Kotlin, String and String? are different types, and the type system tracks the difference:

Kotlin String and String? are different types (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.

For id 2 the name would be null. The compiler rejects the call: error: argument type mismatch: actual type is 'String?', but 'String' was expected. You must say what happens in the null case: lengthOf(input ?: ""), input?.let { lengthOf(it) }, or an explicit check. Moving a type down the hierarchy from String? to String is only possible once you prove the value is not null.

Nothing: the type of "never returns"

Nothing is the bottom of the hierarchy. A function returning Nothing never returns normally (it throws or loops forever). Since Nothing is a subtype of every type, an expression of type Nothing can stand where any type is expected. That is the secret behind idioms like ?: return and ?: error(...):

Kotlin Nothing fits everywhere

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.

Each fail(...) has the type Nothing, which is a subtype of String and Int, so the elvis expression (?:) typechecks. The compiler also knows the code after a Nothing call is unreachable, which is why number can be used afterwards without a null check. The standard error(), TODO() and throw itself are all Nothing.

Nothing also appears in inferred types. listOf(null) gets the type List<Nothing?>, and because Nothing? is a subtype of every nullable type and List is covariant (Variance), that one list fits any list of nullable elements. An emptyList() with no hint is a List<Nothing>, which fits any list at all:

Kotlin Lists of Nothing fit every list 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 same list object is accepted as List<String?> and as List<Int?>, and the empty one as List<String> and List<Int>. This is why emptyList() can be returned from any function with a list result. A bare val x = emptyList() is a different matter: it fails with error: cannot infer type for type parameter 'T'. Specify it explicitly., because there is nothing to choose T from, and you must say which list type you mean.

Unit: the "no useful result" value

Unit is a normal type with exactly one value. Functions without a declared result return it. Because Unit is a real type, it works in generics, where Java's void does not: Result<Unit>, List<Unit>, () -> Unit all make sense.

Kotlin Unit is a real value

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.

greet has no return type written, so it is Unit. The variable result holds the single Unit object, which prints as kotlin.Unit. You almost never need that, but it shows that "returns nothing" and Nothing are opposites: a Unit function does return; a Nothing function never does.

Platform types: the types from Java

Kotlin calls Java constantly. Java has no nullability in its types, so a Java method returning String may return a string or null, and nothing in the signature says which. Kotlin cannot give such a result String (it might lie) or String? (it would force a null check after every Java call). It uses a third option, a platform type, written String! in IDE hints and error messages. You cannot write it yourself. It means: "I do not know; you decide, and you carry the risk."

Kotlin A platform type can be treated either way

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 use is safe. The second one asserts "this is not null" by declaring a String, and since the value really is null, the program fails at the assignment with a NullPointerException, not later when risky is used somewhere far away. That early failure is the benefit of the compiler's generated check. The rule of thumb for professionals: at every Java boundary, decide the nullability and write it down (val s: String? = javaCall()), so the platform type does not spread through your code. See Java Interoperability.

Intersection types and smart casts

When you test a value with is, the compiler remembers the result and treats the value as the narrower type in the code where the test is known to hold. This is a smart cast. If you test twice, the value is smart cast to both types at once, an intersection type that you cannot write in a declaration, but which the compiler tracks:

Kotlin One value, two smart casts

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, creature is not Any any more; it is "Walks and Swims", so both calls compile without casts. The same mechanism makes if (x != null) x.length work: after the check, x is String, not String?. Also, because Duck is a Walks, you could have declared the parameter as Any and still never needed a manual cast.

The compiler also infers intersection types for the common supertype of different values. The type of if (flag) 1 else "one" is not "Int or String" (Kotlin has no union types), but the most specific type they share, and for these two classes that includes Comparable and Serializable:

Kotlin No union types: the common supertype

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 input box is preset to yes, so the program prints 1 twice and then the class name Int; change the input to anything else and it prints one twice and String. The static type of either is one thing, its run-time class another. Remember the two views of a value: the static type is what the compiler can prove and decides which members you may call; the run-time class is what the object really is and decides which overriding method executes.

When a smart cast works, and when it does not

The compiler only smart casts when it can prove the value cannot change between the check and the use. The rules, in order of how often they matter:

  1. Local val: always stable. Smart casts work.
  2. Local var: works if it is not modified between the check and the use and is not captured by a lambda that modifies it.
  3. val property of the same module, without a custom getter and not open: works.
  4. var property: never smart cast, because another thread or a function call could change it.
  5. Properties from another module, or with a custom getter, or open: never, because the compiler cannot know they return the same value twice.
Kotlin A mutable property is not smart cast (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 explains: error: smart cast to 'String' is impossible, because 'nickname' is a mutable property that could be mutated concurrently. The fixes are to copy the value into a local val, or to use a safe call. Copying is the most common one:

Kotlin Copy into a local val to get a stable value

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.

This is the same reasoning behind the advice to prefer val and immutable classes (Variables): immutability makes both programs and the compiler's proofs easier. The follow-up topic, Smart Casts and Contracts, shows how functions like require and isNullOrEmpty teach the compiler new facts.

Other types worth knowing

  • Function types such as (Int) -> String are ordinary types, with variance rules of their own (Variance).
  • Type aliases (typealias Handler = (Event) -> Unit) are only another name; they do not create a new type (Function Types and Type Aliases).
  • Value classes are distinct types that usually disappear at run time (Value Classes).
  • Primitive types Int, Double and the rest are classes in Kotlin source; the compiler uses JVM primitives whenever it can, and boxes them for Int? or generic use.
  • Arrays keep their element type at run time, unlike generics (Arrays).

Putting it together

Next time you hit a type error, ask three questions: (1) Which two types does the compiler say clash, and which is the subtype? Assigning up is free; assigning down needs proof. (2) Is nullability involved (T versus T?)? (3) Does the value come from Java, so that a platform type is involved? Most messages you see are answers to one of these.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type is a subtype of every other Kotlin type?

    Nothing is the bottom of the hierarchy and has no values. Because it is a subtype of everything, a throw or a Nothing-returning function can appear wherever any type is expected. Any? is the top, not the bottom.
  2. 2. What does String! in a compiler message or IDE hint indicate?

    Java types carry no nullability, so Kotlin uses a platform type and lets you treat it as either String or String?. The risk of null is yours.
  3. 3. Why is if (obj.name != null) obj.name.length rejected when name is a var property?

    Smart casts need a stable value. A mutable property might be reassigned (even by another thread) after the check. Copy it to a local val or use a safe call.
  4. 4. What is the type of val x = if (flag) 1 else "one"?

    Kotlin infers a common supertype. For Int and String that is an intersection of shared interfaces such as Comparable and Serializable, which can be assigned to Any or Comparable<*>.
  5. 5. How do Unit and Nothing differ?

    Unit is the 'no useful result' type with a single value. Nothing means the code never completes normally (it throws or loops forever), and it has no value at all.

Summary

  • Any? is the top of the hierarchy, Any the top of the non-null types, Nothing the bottom; each class C has a nullable twin C? that is a supertype of C.
  • Nullability is part of the type: String? does not go where String is required until you check, default or assert.
  • Nothing is a subtype of everything, which is why throw, error() and ?: return fit into any expression.
  • Unit is an ordinary type with one value; it is what "returns nothing" really returns.
  • Types coming from Java are platform types (String!): decide their nullability at the boundary and write it down.
  • A successful is or null check smart casts a stable value, even to an intersection of several types; local vals and unchanging val properties qualify, var properties do not.
  • There are no union types: a mixed if or a mixed list gets the common supertype.

Next: Kotlin Idioms