Introduction to Kotlin

Introduction to Kotlin in Kotlin: --- A freight depot in Wakefield has kept its consignment ledger in the same longhand notation since 1974.


The Analogy: The Bilingual Ledger at a Freight Depot

A freight depot in Wakefield has kept its consignment ledger in the same longhand notation since 1974. Every entry names the sender, the receiver, the declared weight, the rate band and the van; every field is written out in full, and a clerk who has nothing to put in a field is expected to write NIL rather than leave a gap. The notation is verbose -- eleven marks for a consignment that differs from yesterday's only in its weight -- but the auditors know it cold. Any of them can lift a page from any year, from any depot in the group, and read it without asking a question.

In 2011 the head clerk introduces a second notation on the same pages. It is deliberately terser: a consignment that goes out on the usual van at the usual rate needs three marks instead of eleven, because the new notation lets a clerk write only what differs from the standing arrangement. The important thing is not the brevity. It is that the terse entries are posted into the same ledger, on the same ruled lines, in the same ink, and the auditor's monthly totals still come out right. A single page can carry longhand entries above the fold and terse entries below it, and the man who adds up the column does not need to know which is which. That is Kotlin and Java on the JVM: two notations, one ledger of bytecode, one runtime adding up the column.

The terse notation also brings in one hard rule the longhand never had. A field that is genuinely allowed to be empty must be marked with a small circle beside it, and a field without a circle may never be left empty. The head clerk enforces this with a red pen at the moment of writing, before the page is filed -- not later, not by the auditor. This is what the second notation is actually for. Brevity is pleasant, but the reason the depot adopted it is that one entire class of mistake, reaching for a field that nobody ever filled in, is now caught by the clerk who made it rather than by a van driver at four in the morning. Kotlin spells the small circle as a question mark, and the red pen is the compiler.

Where it breaks is the seam. Longhand entries carry no circles, because the longhand notation has no concept of one. So when a terse entry copies a value out of a longhand entry, the head clerk has nothing to check it against: the old page simply does not record whether that field was permitted to be blank. The clerk waves it through, the page is filed, and if that longhand field happened to be empty on the day, the terse entry that depended on it fails when the van is loaded -- not when the page was written. Every one of the depot's oldest, ugliest failures lives exactly there, at the boundary between the two notations, and none of them are visible on the page. Kotlin calls those unmarked values platform types, and they are the one place where the compiler's guarantee quietly stops.


Syntax or Core Structure

The smallest complete Kotlin program is a top-level function named main. There is no enclosing class to declare, no static modifier, and no public keyword, because all three are already the defaults.

fun main() {
    val depot = "Wakefield"        // read-only; type inferred as String
    var vansOut = 3                // reassignable
    vansOut = vansOut + 1

    println("Depot: $depot")
    println("Vans out: $vansOut")
    println("Status: " + describe(vansOut))
}

fun describe(n: Int): String {
    return if (n > 3) "busy" else "quiet"
}

Output:

Depot: Wakefield
Vans out: 4
Status: busy

Four things in twelve lines are worth naming. val declares a binding that cannot be reassigned and var one that can, and the type of both is inferred from the initialiser -- depot is a String and vansOut is an Int without either word appearing. A $ inside a double-quoted string splices a value in, so "Vans out: $vansOut" needs no concatenation operator. describe declares its return type after the parameter list, and its body is an if that produces a value rather than choosing between two assignments. And nothing on any line ends in a semicolon; Kotlin's grammar makes them optional, and idiomatic Kotlin omits them.


Technical Depth: How Kotlin Reaches the Machine

Four back ends, one language

Kotlin is not defined by a single output format. The same source language is compiled by four different back ends, and which one you are using changes what the standard library can offer you and what interop looks like.

TargetWhat the compiler emitsWhere it runs
Kotlin/JVMJava class files holding JVM bytecodeAny JVM, and Android after dexing
Kotlin/JSJavaScript modules, optionally with .d.tsBrowsers and Node
Kotlin/NativeMachine code produced through LLVMiOS, macOS, Linux, Windows
Kotlin/WasmWebAssembly modulesWasm-capable browsers and runtimes

Everything in this course targets Kotlin/JVM, which is also what Android uses. That matters for a reason beyond convenience: on the JVM your Kotlin sits in the same class-loading, garbage-collecting, exception-throwing world as every Java library you already depend on, so interop is not a bridge you cross but the ground you are standing on.

Where a top-level declaration actually lands

Kotlin lets you declare functions and properties at the top level of a file, outside any class. The JVM does not allow that, so the compiler invents a container. A file called Depot.kt produces a class named DepotKt.

Kotlin declaration in Depot.ktBytecode shape on the JVM
A top-level funa static method on a generated class named DepotKt
A top-level vala private static field plus a static getter on DepotKt
A top-level const vala static final field whose value is inlined at every call site
A member fun inside class Vanan ordinary instance method on Van
An object declarationa class holding a static INSTANCE field

The practical consequence is that Java can call your top-level Kotlin function as DepotKt.describe(4), and that const val is not merely a style choice: because its value is inlined, changing it forces a recompile of every module that read it, whereas changing a plain val only forces a recompile of the file that declares it.

Unit is a real type, not a hole

Kotlin has no void. A function that returns nothing returns Unit, a type with exactly one value, and that value is an object you can bind and print. This sounds like pedantry until you meet generics, where void cannot be a type argument and Unit can.

fun greet(name: String): Unit {
    println("Hello, $name")
}

fun shout(name: String) = println("HELLO, ${name.uppercase()}")

fun main() {
    greet("Wakefield")
    shout("Wakefield")

    val ack: Unit = greet("Leeds")
    println("greet returned: $ack")
}

Output:

Hello, Wakefield
HELLO, WAKEFIELD
Hello, Leeds
greet returned: kotlin.Unit

Note the second declaration. shout has no braces and no return type: an equals sign followed by a single expression is a complete function body, and its return type is inferred from that expression. Because println returns Unit, so does shout. This expression-body form is the one you will write most often, and the compiler will still stop you if you declare a return type the expression cannot produce.

Almost everything is an expression

In Java, if, switch and try are statements: they direct control flow but they do not produce a value, so a value that depends on a branch has to be assigned to a mutable variable inside each arm. Kotlin makes all three expressions, which is why val is a realistic default rather than an aspiration.

fun main() {
    val load = 140

    val band = if (load > 200) "heavy" else if (load > 100) "medium" else "light"
    println("Band: $band")

    val fee = when (band) {
        "heavy"  -> 40
        "medium" -> 25
        else     -> 10
    }
    println("Fee: $fee")

    val parsed = try {
        "12x".toInt()
    } catch (e: NumberFormatException) {
        println("rejected by " + e::class.simpleName)
        -1
    }
    println("Parsed: $parsed")

    val label = when {
        fee >= 40 -> "premium"
        fee >= 25 -> "standard"
        else      -> "economy"
    }
    println("Label: $label")
}

Output:

Band: medium
Fee: 25
rejected by NumberFormatException
Parsed: -1
Label: standard

Trace the third one carefully, because the ordering is the point. The try block runs, toInt throws, the catch arm runs and prints its line, and the value of the whole try expression becomes -1 -- which is only then bound to parsed and printed. A try used as an expression yields the last expression of whichever block completed. The final when has no subject at all: each arm is a boolean condition, which is Kotlin's replacement for a chain of else if.


Real World Example: The Depot's Nightly Manifest Total

The depot's night clerk receives the day's manifest as one line per consignment and has to produce three figures before the vans are dispatched: how many consignments were read, the total weight per destination, and the single heaviest load. The whole job is about twenty lines of Kotlin, and it exercises every feature introduced above.

// One consignment per line: id;destination;weightKg
const val MANIFEST =
    "C001;LEEDS;120\nC002;HULL;80\nC003;LEEDS;45\nC004;YORK;200\nC005;HULL;15"

class Consignment(val id: String, val destination: String, val weightKg: Int)

fun parseLine(line: String): Consignment {
    val parts = line.split(";")
    return Consignment(parts[0], parts[1], parts[2].toInt())
}

fun main() {
    val rows = MANIFEST.lines().map(::parseLine)
    println("Consignments read: ${rows.size}")

    val totals = mutableMapOf<String, Int>()
    for (row in rows) {
        totals[row.destination] = (totals[row.destination] ?: 0) + row.weightKg
    }

    for (destination in totals.keys.sorted()) {
        println("$destination -> ${totals.getValue(destination)} kg")
    }

    var grand = 0
    for (row in rows) {
        grand += row.weightKg
    }
    println("Total: $grand kg")

    val heaviest = rows.maxByOrNull { it.weightKg }
    if (heaviest == null) {
        println("Heaviest: none")
    } else {
        println("Heaviest: ${heaviest.id} at ${heaviest.weightKg} kg to ${heaviest.destination}")
    }
}

Output:

Consignments read: 5
HULL -> 95 kg
LEEDS -> 165 kg
YORK -> 200 kg
Total: 460 kg
Heaviest: C004 at 200 kg to YORK

Read the arithmetic rather than trusting it. HULL takes 80 from C002 and 15 from C005, which is 95. LEEDS takes 120 from C001 and 45 from C003, which is 165. YORK takes 200 from C004 alone. Those three figures add to 460, and the independent grand loop over all five rows adds 120, 80, 45, 200 and 15 to the same 460. Two different traversals agreeing is the only reason to believe either of them.

The Kotlin doing the work is worth naming line by line. MANIFEST.lines() splits on newlines and returns a List<String>; map(::parseLine) passes a reference to a named function where a lambda would otherwise go, using the :: operator. Inside the accumulation loop, totals[row.destination] returns Int? rather than Int, because a map lookup can miss -- and ?: 0 supplies the fallback, so the arithmetic that follows is on a plain Int. The class declaration is a single line: three val parameters in the primary constructor become three read-only properties, no field declarations and no getters written by hand.

Two decisions in that listing are there purely for determinism, and both are habits worth forming now. Iterating totals.keys.sorted() rather than totals means the destination lines come out in a fixed order regardless of what the map's internal layout happens to be -- mutableMapOf gives you insertion order today, but nothing in the type says so. And maxByOrNull returns Consignment? because an empty list has no maximum, so the result is checked with an explicit if before either of its properties is read. The compiler will not let you skip that check, which is the small circle in the ledger doing its job.

The limits are real. The manifest is a compile-time constant, so this program is a demonstration and not a tool: the first thing production would need is to read from a file or a socket, which immediately introduces the failure paths this version does not have. The heavier problem is parseLine, and it is a design flaw rather than a rough edge. Its signature promises a Consignment for any String you hand it, and that promise is false three ways: a line with two fields throws IndexOutOfBoundsException at parts[1], a line with a non-numeric weight throws NumberFormatException at toInt, and a line with a negative weight is accepted silently and quietly corrupts the totals. The type system has been told nothing about any of this, so every caller inherits an unchecked failure it cannot see. A second, milder flaw sits alongside it: the grand total is computed by its own loop instead of from totals, so the two figures are only equal by coincidence of maintenance -- change the accumulation to skip a destination and the total will keep reporting the old number. Returning a nullable Consignment?, or a sealed result type, and folding the grand total out of totals would fix both.


Common Mistakes

  1. Reaching for var by default. Java programmers arriving in Kotlin declare var everywhere because that is what a bare Java local is. The habit costs you the compiler's help: a val cannot be clobbered by a later edit, and because if, when and try are expressions, almost every var you were about to write can be a val initialised from a branch.
  1. Using !! as a compiler silencer. The !! operator does not check anything; it converts a compile-time complaint into a runtime NullPointerException at a line you have chosen. If you find yourself writing it more than once or twice in a file, the nullable type is telling you something true about the data and the fix belongs upstream.
  1. Wrapping top-level functions in a pointless class. Writing class DepotUtils { companion object { fun describe(n: Int) = ... } } reproduces a Java workaround Kotlin does not need. A top-level fun already compiles to a static method; the wrapper only adds a name your callers have to type.
  1. Forgetting else in a when used as an expression. A when used as a statement may omit else. A when whose value you assign must be exhaustive, and the compiler will refuse it. The error message names the missing branch, so read it rather than adding else -> throw reflexively.
  1. Believing val freezes the object. val makes the binding read-only, not the thing it points at. val rows = mutableListOf<Int>() still allows rows.add(1). Immutability of contents is a separate decision, made by choosing listOf over mutableListOf.
  1. Assuming a value returned from Java is non-null. Java declarations without nullability annotations arrive in Kotlin as platform types, written String! in error messages. The compiler permits both nullable and non-null use, checks neither, and the failure surfaces at the call site. Annotate the Java side, or narrow the value into a Kotlin nullable at the boundary.
  1. Using == when you meant identity. In Kotlin == calls equals, which is the opposite of Java's default for objects. If you genuinely need reference identity -- comparing two cache entries, say -- the operator is ===.
  1. Writing return inside an expression-bodied function. fun describe(n: Int) = return if (n > 3) "busy" else "quiet" does not compile. An equals sign introduces the value itself, so the return keyword belongs only in a block body wrapped in braces.
  1. Assuming Int and Int? have the same representation. A non-null Int compiles to the JVM primitive int. An Int? cannot, because a primitive has no null, so it compiles to java.lang.Integer and every use boxes. In a tight numeric loop that single question mark is the difference between no allocation and one allocation per iteration.

Best Practices

  • Declare val first and demote to var only when a reassignment actually appears. Write the val, let the compiler complain, then change it. The complaint is cheaper than the bug.
  • Let inference handle local types; write return types on anything public. val n = 4 is clearer without : Int, but a public function's return type is part of its contract and should not silently change when you edit the body.
  • Prefer string templates to concatenation. "Total: $grand kg" reads better than the + chain and avoids the accidental Int addition that "a" + 1 + 2 invites.
  • Use an expression body for any function that is one expression. fun describe(n: Int) = if (n > 3) "busy" else "quiet" states exactly what the function is, and the inferred type is checked against every caller.
  • Return the value of a when instead of assigning inside its arms. One binding, one place the result is produced, and exhaustiveness checked for you.
  • Sort before you print any map or set. Iteration order of a hash-based collection is not part of its contract, so a test or a log line that depends on it is a future flake. keys.sorted() costs nothing at these sizes.
  • Annotate the Java side of every boundary you own. Adding @Nullable and @NotNull to Java signatures collapses platform types into real Kotlin types and moves those failures from runtime to compile time.
  • Turn warnings into errors from the first commit. Setting allWarningsAsErrors in the Gradle Kotlin options keeps deprecations, unused bindings and unchecked casts from accumulating into noise nobody reads.

Practice Exercises

  1. Harden the parser. Change parseLine to return Consignment?, returning null for any line that does not have exactly three semicolon-separated fields, whose weight is not a valid integer, or whose weight is negative. Then adjust main so malformed lines are counted and reported separately from accepted ones, and confirm the accepted total still comes to 460 for the original manifest.
  1. Remove the duplicate total. Delete the grand loop and derive the grand total from totals instead. Prove the two approaches agreed before you deleted one by printing both figures side by side in an intermediate version, then keep only the derived figure.
  1. Make the bands a single source of truth. The example decides the band with an if chain and the fee with a when on the band's string, which means a typo in one string breaks the pairing silently. Rewrite both as one when over the numeric load that produces the band and the fee together, and show that a load of 140 still yields medium and 25.
  1. Watch the seam. Write a two-line Java class with a method static String depotName() that returns null, call it from Kotlin as val name: String = Depot.depotName(), and record exactly where the failure appears -- compile time or run time, and on which line. Then add @Nullable to the Java method and record what changes.