Kotlin Fast Track
K

Kotlin Fast Track

Kotlin syntax and semantics for someone who already writes Python and C. Each idea shows the Kotlin way and, where it helps, how it maps to what you know.

Covers
Guide sections 1–17 · portfolio weeks 1–5
Legend
PYvs Python Cvs C !gotcha TIPidiom
Keys
/ search · tick the boxes in the sidebar as you go

01What's different #

The mental model in one screen. If you read nothing else, read this.

Static types, inferredC-level type safety, Python-level brevity. val n = 3 is an Int forever.
val vs varval = can't reassign (like const pointer, not deep-const). Default to val.
Everything is an expressionif, when, try return values. No ?: ternary needed.
Null is in the typeString can never be null. String? can, and the compiler forces you to handle it.
No new, no semicolonsval p = Point(1, 2). Newlines end statements.
Classes are final by defaultMust write open to allow subclassing and override to override.
Properties, not fieldsp.x calls a getter. You can give it a custom get()/set() later without changing callers.
== is equalityCalls equals(). Strings compare by content. === is identity (C pointer compare / Python is).
Read-only collections by defaultlistOf() has no add. Use mutableListOf() when you need it.
Top-level functionsNo class wrapper needed (unlike Java). fun main() is the entry point.
Extension functionsAdd methods to existing types: fun String.shout() = uppercase() + "!".
Runs on the JVMCompiled to bytecode. Any Java library works. Int is a JVM int when possible.

02Python → Kotlin phrasebook #

Look up the thing you'd write in Python and find the Kotlin (and C) version.

PythonKotlinC
x = 5val x = 5 / var x = 5int x = 5;
print(f"a={a}")println("a=$a")printf("a=%d\n", a);
f"{x:.2f}""%.2f".format(x)"%.2f"
len(xs)xs.size · s.lengthstrlen(s) / manual
range(n)0..<n or 0 until nfor(i=0;i<n;i++)
range(1, n+1)1..n (inclusive)i<=n
for i, v in enumerate(xs)for ((i, v) in xs.withIndex())index loop
a if c else bif (c) a else bc ? a : b
match x:when (x) { … }switch
and or not&& || !&& || !
a // ba / b (both Int, truncates)a / b
a ** ba.pow(b) (Double) — no operatorpow(a, b)
Nonenull (type must be T?)NULL
x or defaultx ?: default—
[1, 2, 3]listOf(1, 2, 3) / mutableListOf(…)int a[] = {1,2,3};
{"a": 1}mapOf("a" to 1)—
(a, b) tuplePair(a, b) / a to b / Triplestruct
[x*2 for x in xs if x>0]xs.filter { it > 0 }.map { it * 2 }loop
lambda x: x + 1{ x -> x + 1 } or { it + 1 }function pointer
sum(xs) max(xs)xs.sum() xs.max()loop
sorted(xs) / xs.sort()xs.sorted() / xs.sort() (mutable only)qsort
isinstance(x, T)x is T—
raise ValueError("m")throw IllegalArgumentException("m")return code
assert c, "m" (validate args)require(c) { "m" }assert(c)
try/except E as etry { } catch (e: E) { }—
with open(f) as h:… .use { h -> }fopen/fclose
class P: def __init__class P(val x: Int)struct
__str__ / __eq__override fun toString() / equals (or data class)—
@staticmethodcompanion object { fun … }plain function
pass{} or Unit;
sys.argv[1:]args (already excludes program name)argv + 1
sys.exit(1)exitProcess(1)exit(1)
input()readln()fgets

03Programs & the toolchain #

What a program looks like and how you build and run it.

PY

args does not include the program name. args[0] is the first user argument, unlike sys.argv[0] and C's argv[0].

Commands you'll use

CommandDoes
./kotlin run a b cBuild, then run with args. echo $? afterwards shows the exit status.
./kotlin buildCompile only. Use it to see compiler errors fast.
./kotlin testRun everything in test/.
./kotlin test -m trianglesRun tests for one module (a subdirectory with its own module.yaml).
./kotlin run -m redact …Run one module's app.
./kotlin cleanDelete build output (do this before zipping a submission).
./gradlew run / testSame jobs in the Gradle-based tasks.
  • Layout: module.yaml (product: jvm/app), code in src/, tests in test/.
  • All .kt files in src/ without a package line share one namespace. A top-level function in Stats.kt can be called from Main.kt without importing it.
  • File names don't have to match class names (unlike Java), but convention is one main class per file, named after it.

04Variables, types, numbers #

Types come after the name. Numbers are strict about conversions.

KotlinC equivalentRange / notes
Intint32_t±2.1 billion. The default for whole-number literals.
Longint64_tSuffix L. Use for sums that can get large.
DoubledoubleThe default for 1.5.
FloatfloatSuffix f.
Booleanbooltrue/false. Ints are not truthy.
Charchar (16-bit)'a'. Not a number: 'a' + 1 is 'b', 'a'.code is 97.
Stringchar*Immutable object. Compare with ==.
UnitvoidThe return type when nothing is returned.

Conversions are always explicit

Arithmetic

!

Int overflow is silent. 92682 * 92682 wraps to a negative number because it's bigger than Int.MAX_VALUE. Python never overflows; C technically has undefined behaviour. Use Long when values can exceed ~2 billion (Task 3.2, Task 4.5).

05Strings #

Templates replace f-strings. Methods are close to Python's.

PythonKotlin
s[0], s[-1]s[0] (a Char), s.last()
s[1:4]s.substring(1, 4) or s.slice(1..3)
s.upper() / lower()s.uppercase() / lowercase()
s.strip()s.trim()
s.split(",")s.split(",") → List<String>
",".join(xs)xs.joinToString(",")
s.replace(a, b)s.replace(a, b) (also ignoreCase = true)
"ab" * 3"ab".repeat(3)
sub in ssub in s or s.contains(sub)
s.startswith(p)s.startsWith(p)
s.find(x)s.indexOf(x) (−1 if missing)
s[::-1]s.reversed()
s.isdigit()s.all { it.isDigit() }
not s.strip()s.isBlank() (isEmpty() only checks length 0)
str(x)x.toString() or "$x"
ch * n (char)ch.toString().repeat(n)

Building strings in a loop

TIP

The String API is large. When a task hints "look at the String docs", check kotlinlang.org/api/…/-string under Members & Extensions. Most Python string methods have a direct equivalent there.

06Control flow #

if and when return values. for always iterates over something.

if as an expression

when — switch on steroids

C

No fall-through and no break needed. Each branch is independent.

Loops and ranges

C

There's no for (i = 0; i < n; i++). Use a range. Kotlin also has no switch, no ternary ?: (that symbol means something else, see §08), and no comma operator.

07Functions #

Types after names, return type after the parens. One-liners use =.

Defaults, named args, varargs

Special return types

Extension functions & properties

Add members to a type you don't own. Inside the body, this is the receiver. Nothing is patched at runtime: it's a static function that you call with dot syntax.

PY

Arguments are passed by reference to objects, as in Python, but parameters are always val. You can't reassign a parameter inside the function.

08Null safety #

This is where Kotlin differs most from Python and C. Learn these operators and you'll understand most Kotlin code.

OperatorMeaningExample
?.Safe call. Returns null instead of crashing.b?.length → Int?
?:Elvis. "If the left side is null, use this instead."b?.length ?: 0 → Int
!!"Trust me, it's not null." Throws NPE if it is. Avoid.b!!.length
?.let { }Run a block only when the value isn't null.b?.let { println(it) }
as?Safe cast. Gives null if the cast fails.x as? String
!

Common sources of nullable values: map[key], toIntOrNull(), firstOrNull(), maxByOrNull(), readlnOrNull(), getOrNull(i). When you see "type mismatch: inferred type is String? but String was expected", one of these is usually the cause (Task 10.1).

Smart casts don't work on var properties, because another thread could change them. Copy the value into a local val first.

09Exceptions #

Java's exceptions without checked exceptions. try is an expression.

UseThrowsWhen
require(cond) { msg }IllegalArgumentExceptionThe caller passed a bad argument. Use it in init blocks and setters.
check(cond) { msg }IllegalStateExceptionThe object is in the wrong state for this call.
requireNotNull(x)IllegalArgumentExceptionReturns x as non-null.
PY

ValueError maps to IllegalArgumentException. IndexError maps to IndexOutOfBoundsException. KeyError has no equivalent: map[k] returns null instead (getValue(k) throws).

10Collections #

Read-only and mutable versions of List, Set and Map. Pair and Triple act as tuples.

Pair, Triple, destructuring, typealias

Arrays vs lists

!

val list = mutableListOf(1): the reference can't change, but you can still call list.add(2). val ≠ immutable. List is also only a read-only view, not a guaranteed-immutable object.

11Lambdas & collection ops #

Most collection work in Kotlin uses these instead of loops. Portfolio weeks 3–4 rely on them heavily.

Cheat sheet

OpResultPython-ish
map { }List[f(x) for x in xs]
filter { } / filterNotList[x for x in xs if p(x)]
count { }Intsum(1 for x in xs if p(x))
sum() / sumOf { }numbersum(f(x) for x in xs)
average()Doublestatistics.mean (NaN if empty)
min() max() / minOf { }element / valuemin(xs) (throws if empty)
maxBy { } / minByOrNull { }elementmax(xs, key=f)
sortedBy { } / sortedByDescendingListsorted(xs, key=f)
any { } all { } none { }Booleanany(...)
first { } / firstOrNull { }elementnext(x for x in xs if p(x))
groupBy { }Map<K, List>itertools.groupby-ish
partition { }Pair<List, List>—
associate { k to v }Map{k: v for …}
distinct() toSet()List / Setset(xs)
take(n) drop(n)Listxs[:n] xs[n:]
zip(ys) chunked(n) windowed(n)Listzip
flatMap { }Listnested comprehension
forEach { }Unitfor loop
removeAll { } / retainAll { }Boolean (changed?)in-place filter, MutableList only

Scope functions (you'll see these everywhere)

FnInside, object isReturnsTypical use
letitlambda resultx?.let { … } null handling
applythisthe objectconfigure after creating: Person().apply { age = 3 }
alsoitthe objectside effects: .also { println(it) }
run / withthislambda resultcompute something from an object's members
useitlambda resultauto-close files, like Python's with
Sequences (lazy evaluation, Task 8.4.2)

List ops are eager: each step builds a whole new list. asSequence() makes the chain lazy, like a Python generator, so each element flows through the whole chain one at a time. This is faster for big data or when you stop early with first/take.

Returning from inside a lambda

A bare return inside forEach { } returns from the enclosing function, not just the lambda. Use return@forEach to skip to the next element, like continue.

12Input & files #

kotlin.io.path extension functions on Path.

TIP

java.io.File("x").readLines() also works. The course uses Path. Dates use kotlinx.datetime: LocalDate.parse("2026-10-16"), and you compare them with <, > and ==.

13Classes & properties #

The constructor goes in the header. val/var there declares a property.

PY

No self parameter. Members are in scope directly, and this exists when you need it (e.g. this.x = x). Without override fun toString(), println(p) prints Point@1b6d3586.

Constructors: primary, init, secondary

TIP

Default arguments in the primary constructor usually remove the need for secondary constructors: class Point(val x: Int = 0, val y: Int = 0).

Stored vs computed properties

!

If the value depends on a var that can change, it must be a computed get(). Otherwise it stays stale. For a UML attribute marked [computed], use get().

Custom getters/setters and field

!

The initializer (= 5) writes directly to the field. It does not go through the setter, so a default value isn't validated. Also, protected set means subclasses can assign the property but outside code can't.

What it compiles to (Task 12.5.1)

val x becomes a private field plus getX(). var x also gets setX(). A computed get() property has no field at all. Run javap -p on the .class file to see this.

14Data, enum, object #

Three kinds of class that save you writing boilerplate.

data class

Python equivalent: @dataclass(frozen=True). You can still override toString() in a data class.

enum class

object and companion object

15Inheritance & interfaces #

Classes and members are closed by default. You explicitly allow subclasses to extend or override them.

PY

Header syntax: class Dog(...) : Animal(name) replaces Python's class Dog(Animal) + super().__init__(name). Single inheritance for classes. Multiple interfaces are allowed.

Abstract classes

Interfaces

abstract classinterface
State (backing fields)yesno (properties must be abstract or computed)
Constructoryesno
How many per classonemany
Use for"is-a" with shared code/state"can-do" capability

Type checks & casts

TIP

If you find yourself writing if (s is Circle) … else if (s is Rect) …, move the behaviour into an overridden method instead (Tasks 15.4.1 → 15.4.2). sealed class gives exhaustive when over subclasses, if you want that.

16Packages & visibility #

ModifierVisible toPython / C analogue
public (default)everyonenormal names / header-exposed
privatethis class (or this file, if top-level)_name convention / static in C file
protectedthis class + subclasses—
internalsame module—

Tests in test/ must use the same package (or import it) to see your classes.

17Testing with Kotest #

The portfolio uses Kotest FreeSpec. Each string is a test name and each block is the test.

MatcherAsserts
a shouldBe b / shouldNotBea == b
x shouldBe (y plusOrMinus tol)float tolerance (import from doubles or floats to match the type)
shouldThrow<T> { }block throws T; returns the exception
shouldNotThrowAny { }no exception
list shouldHaveSize n, shouldContain x, shouldBeEmpty()collections
s shouldStartWith "x", shouldContain "x"strings
b.shouldBeTrue()boolean

Choosing good test cases

  • Each test should fail against a plausible wrong implementation. For example, if your input is already sorted, the test won't catch a missing sort.
  • Cover the boundaries: empty, one element, even vs odd size, negatives, duplicates, values on range edges (39/40, 69/70).
  • Give each test a name that says what it checks, e.g. "median of unsorted even-length list".
  • Write a stub first (fun f(): Double = 0.0) so the tests compile, see them fail, then implement.
kotlin.test version (Task 6.3)

18Gotchas #

Things that catch people coming from Python and C.

You wroteWhat happensFix
7 / 23 (Int division)7 / 2.0 or .toDouble()
for (i in 0..n)runs n+1 times0..<n / until
val area = w * h in a classstale if w changesval area get() = w * h
set(v) { prop = v }infinite recursion → StackOverflowErrorfield = v
class B : A()"This type is final"mark A open or abstract
fun toString()"hides member of supertype"override fun toString()
val x: Long = someInttype mismatchsomeInt.toLong()
sqrt(2)no Int overloadsqrt(2.0)
map[key].lengthwon't compile (nullable)map[key]?.length ?: 0
listOf(1).add(2)no add on ListmutableListOf
println(array)[I@6d06d69ccontentToString()
shouldBe 0.1 + 0.2fails on floating pointplusOrMinus
when (x) { … } as value"must be exhaustive"add else
'a' == "a"compile error: Char vs Stringpick one type
Int.MAX_VALUE + 1silently negativeLong
printing extra outputauto-graders compare exact stdoutprint only what the spec says

19Portfolio map #

What each week tests and which sections of this guide to read first. This is syntax to know, not solutions.

WK 1

Heron's formula CLI

Read args, fail fast with exit status 1, parse Doubles, print exactly 5 decimal places. Check with ./kotlin build && python check.py.

args.sizeexitProcess(1)toDouble()sqrt"%.5f".format()
WK 2

Triangle functions + redact()

Functions that take a typealias'd Triple, return values without printing, default Char parameter. All 16 tests must pass.

typealiasval (a, b, c) = tfun f(x: T = …)String extension fns
WK 3

Throwing exceptions + writing Kotest tests

Make functions reject invalid input with IllegalArgumentException. Write 4 well-chosen median tests with float tolerance, and justify them.

require { }shouldThrow<>plusOrMinussorted()size / 2
WK 4

Triangle class + ToDoList

Primary constructor with vals, an init check, computed properties, an exact toString(). ToDoList stubs are mostly one-liners using collection ops. You'll also parse CSV into a data class, an enum and a LocalDate.

val x get() =init { require }count { }filter { }removeAll { }forEachLinesplit(": ")Enum.valueOfLocalDate.parseT? = null
WK 5

StudentAccount extends abstract BankAccount

Subclass with a super-constructor call, override an abstract method, validate in a custom setter, and write to a protected set property from the subclass. Exception messages must match exactly.

package: Base(arg)override funset(value) { require; field = }protected setoverride fun toString()
!

Before you submit: run all the tests, ./kotlin clean if you're zipping, upload only the files each README names, and don't print anything the spec doesn't ask for.