Chrysolites Tech Academy

Programming Foundations: Python, Algorithms, Kotlin and Excel · Course book

Chapter 3: What Kotlin's Compiler Does for You

Pairs with Lesson 3: Kotlin: A Modern Typed Language

Kotlin is a modern language used for Android apps, server software and much else. If Python is relaxed about what a variable may hold, Kotlin is strict, and that strictness is its main selling point: a large class of mistakes is caught before the program ever runs. This chapter explains the ideas behind Kotlin's design so that the syntax you meet in the video has something to hang on.

A compiled, typed language

Python reads your code and carries it out line by line. Kotlin adds a step in between. A program called the compiler first reads the whole of your source code, checks it and translates it into a compact form called bytecode. The bytecode is then run by the Java Virtual Machine, usually shortened to JVM, which exists for almost every kind of computer.

Source codeMain.ktBytecode.class filesJVMruns the program Compiler type and null errors are reported here, before anything runs
Figure 3.1 — From source code to a running program. The compiler is a checkpoint: code with type errors never gets past it.

The checking step works because Kotlin is statically typed: every variable has a type that is fixed when the code is compiled. You declare variables with one of two keywords.

val name = "Amara"      // read-only: cannot be reassigned
var score = 10          // mutable: can be reassigned
score = score + 5       // fine, score is now 15
val limit: Int = 100    // the type written out in full

Notice that the first two lines do not mention a type. The compiler works it out from the value on the right, a feature called type inference. The variable name is a String and score is an Int just as surely as if you had written the types yourself, and trying to store text in score later is a compile error.

Prefer val. A value that cannot change cannot be changed by accident. Experienced Kotlin programmers reach for val first and switch to var only when a variable really has to be reassigned.

Null safety

In many languages any variable might secretly hold "nothing", usually called null, and using it as if it held a real value crashes the program. Kotlin attacks this problem in the type system. An ordinary type such as String can never be null. If a value might be missing you must say so by adding a question mark, giving the type String?.

val city: String = "Lagos"
val nickname: String? = null

println(city.length)        // allowed: city cannot be null
println(nickname.length)    // compile error: nickname might be null

The compiler refuses the last line, so the crash can never reach your users. To work with a nullable value you use one of the tools in Table 3.1.

ToolWritten asWhat it doesResult when the value is null
Safe callnickname?.lengthUses the value only if it existsThe whole expression becomes null
Elvis operatornickname ?: "Guest"Supplies a fallbackThe fallback, here "Guest"
Null checkif (nickname != null)Tests first; inside the block the value is treated as non-nullThe block is skipped
Not-null assertionnickname!!.lengthInsists the value is not nullThe program throws an exception

The first three are safe. The last one switches the protection off and should be rare. Combining the first two is common: nickname?.length ?: 0 gives the length of the nickname, or 0 if there is none.

Functions, lambdas and collections

A Kotlin function states the type of each parameter and of its result, so the compiler can check every call.

fun greet(name: String, greeting: String = "Hello"): String {
    return "$greeting, $name!"
}

greet("Ben")                  // "Hello, Ben!"
greet("Ben", "Welcome")       // "Welcome, Ben!"

The second parameter has a default argument, so callers may leave it out. The dollar signs inside the string insert the values of the variables, which is called a string template.

Kotlin's when is a tidier form of a long chain of if and else. It compares one value against several cases and can produce a result directly:

val grade = when {
    score >= 70 -> "A"
    score >= 50 -> "B"
    else -> "C"
}

A lambda is a small function written inline, between curly braces, and handed to another function as a value. Lambdas make working with collections remarkably concise.

val numbers = listOf(1, 2, 3, 4, 5, 6)
val result = numbers.filter { it % 2 == 0 }
                    .map { it * it }
                    .sum()

Trace it by hand. filter keeps the numbers whose remainder after dividing by 2 is zero, leaving 2, 4 and 6. map squares each one, giving 4, 16 and 36. sum adds them to produce 56. The word it stands for the current item when a lambda takes a single parameter.

Kotlin has three main collections. A List keeps items in order and allows repeats. A Set holds each item once only. A Map links keys to values, like a Python dictionary. Each comes in a read-only form, such as listOf, and a mutable form, such as mutableListOf; only the second lets you add or remove items.

Classes that describe data

A class is a template for objects that bundle related values together with the functions that act on them. Kotlin keeps the common cases short. A data class needs one line:

data class Point(val x: Int, val y: Int)

val a = Point(2, 3)
val b = a.copy(y = 10)     // Point(x=2, y=10)
println(a == Point(2, 3))  // true

From that single line the compiler generates everything needed to compare two points by their contents, print one readably and make an altered copy. In older languages the same class would take dozens of lines.

A sealed class describes a value that must be one of a fixed, known list of kinds, for example a network result that is either a success or a failure. Because the compiler knows the full list, a when that handles a sealed class is checked for completeness: forget one kind and the code does not compile. An extension function lets you add a function to a type you did not write, such as giving every String a new ability, without touching the original class.

Two more keywords are worth recognising. Writing object instead of class creates a singleton, a type with exactly one instance that the whole program shares, which suits things like a settings store. A companion object placed inside a class holds functions and constants that belong to the class as a whole and not to any single instance, so they can be called using the class name alone.

Generics let one piece of code work with many types while staying type-safe. The type List<String> is a list that can hold only strings, and List<Int> one that can hold only whole numbers; the part in angle brackets is a type parameter. The video goes further into variance, the rules marked with the keywords in and out that decide when a list of one type may stand in for a list of another.

Coroutines and flows

Much of what real programs do is wait: for a web server to reply, for a file to load, for a database to answer. If the program simply stops during each wait, an app freezes. Coroutines are Kotlin's answer. A coroutine is a piece of work that can suspend, stepping aside while it waits so that other work can use the same thread, and then resume where it left off.

Suppose a screen needs two pieces of data and each request takes one second. Run one after the other, they take two seconds. Started together with async, they overlap and both are ready after about one second.

SequentialConcurrent one after anotherstarted together Request ARequest BRequest ARequest B 0 s1 s2 stime
Figure 3.2 — Two one-second requests. Run in sequence they finish after 2 seconds; run concurrently in two coroutines they finish after about 1 second.

A few names cover most everyday use. launch starts a coroutine that does a job and returns nothing. async starts one that will produce a result, collected later with await. withContext moves a block of work to a different pool of threads, for instance one intended for reading files. delay pauses a coroutine without blocking the thread underneath it.

Kotlin organises coroutines by structured concurrency. Every coroutine is started inside a scope, and the scope does not finish until all its coroutines have finished. If the scope is cancelled, for example because the user leaves the screen, everything started inside it is cancelled too. Work cannot be lost or left running unnoticed.

A coroutine returns one value. A Flow delivers many values over time, such as a stream of search results or sensor readings. Flows are described as cold: defining a flow does nothing, and its code only starts running when something collects from it. Between the source and the collector you can chain operators such as map and filter, exactly as with a list, except that the values arrive one by one.

Check your understanding

  • What is the difference between val and var, and which should you use by default?
  • Why does the compiler reject nickname.length when nickname has the type String??
  • If nickname is null, what does nickname?.length ?: 0 produce? (Answer: 0, because the safe call gives null and the Elvis operator supplies the fallback.)
  • What is the result of listOf(1, 2, 3, 4).filter { it > 2 }.map { it * 10 }.sum()? (Answer: the filter keeps 3 and 4, the map gives 30 and 40, and the sum is 70.)
  • Three independent requests take 2 seconds each. Roughly how long do they take in sequence, and how long when started together with async? (Answer: about 6 seconds in sequence and about 2 seconds together.)
  • What does it mean to say that a Flow is cold?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.