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.
val n = 3 is an Int forever.val vs varval = can't reassign (like const pointer, not deep-const). Default to val.if, when, try return values. No ?: ternary needed.String can never be null. String? can, and the compiler forces you to handle it.new, no semicolonsval p = Point(1, 2). Newlines end statements.open to allow subclassing and override to override.p.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).listOf() has no add. Use mutableListOf() when you need it.fun main() is the entry point.fun String.shout() = uppercase() + "!".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.
| Python | Kotlin | C |
|---|---|---|
x = 5 | val x = 5 / var x = 5 | int 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.length | strlen(s) / manual |
range(n) | 0..<n or 0 until n | for(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 b | if (c) a else b | c ? a : b |
match x: | when (x) { … } | switch |
and or not | && || ! | && || ! |
a // b | a / b (both Int, truncates) | a / b |
a ** b | a.pow(b) (Double) — no operator | pow(a, b) |
None | null (type must be T?) | NULL |
x or default | x ?: default | — |
[1, 2, 3] | listOf(1, 2, 3) / mutableListOf(…) | int a[] = {1,2,3}; |
{"a": 1} | mapOf("a" to 1) | — |
(a, b) tuple | Pair(a, b) / a to b / Triple | struct |
[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 e | try { } 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) | — |
@staticmethod | companion 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.
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
| Command | Does |
|---|---|
./kotlin run a b c | Build, then run with args. echo $? afterwards shows the exit status. |
./kotlin build | Compile only. Use it to see compiler errors fast. |
./kotlin test | Run everything in test/. |
./kotlin test -m triangles | Run tests for one module (a subdirectory with its own module.yaml). |
./kotlin run -m redact … | Run one module's app. |
./kotlin clean | Delete build output (do this before zipping a submission). |
./gradlew run / test | Same jobs in the Gradle-based tasks. |
- Layout:
module.yaml(product: jvm/app), code insrc/, tests intest/. - All
.ktfiles insrc/without apackageline share one namespace. A top-level function inStats.ktcan be called fromMain.ktwithout 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.
| Kotlin | C equivalent | Range / notes |
|---|---|---|
Int | int32_t | ±2.1 billion. The default for whole-number literals. |
Long | int64_t | Suffix L. Use for sums that can get large. |
Double | double | The default for 1.5. |
Float | float | Suffix f. |
Boolean | bool | true/false. Ints are not truthy. |
Char | char (16-bit) | 'a'. Not a number: 'a' + 1 is 'b', 'a'.code is 97. |
String | char* | Immutable object. Compare with ==. |
Unit | void | The 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.
| Python | Kotlin |
|---|---|
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 s | sub 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
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
No fall-through and no break needed. Each branch is independent.
Loops and ranges
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.
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.
| Operator | Meaning | Example |
|---|---|---|
?. | 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.
| Use | Throws | When |
|---|---|---|
require(cond) { msg } | IllegalArgumentException | The caller passed a bad argument. Use it in init blocks and setters. |
check(cond) { msg } | IllegalStateException | The object is in the wrong state for this call. |
requireNotNull(x) | IllegalArgumentException | Returns x as non-null. |
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
| Op | Result | Python-ish |
|---|---|---|
map { } | List | [f(x) for x in xs] |
filter { } / filterNot | List | [x for x in xs if p(x)] |
count { } | Int | sum(1 for x in xs if p(x)) |
sum() / sumOf { } | number | sum(f(x) for x in xs) |
average() | Double | statistics.mean (NaN if empty) |
min() max() / minOf { } | element / value | min(xs) (throws if empty) |
maxBy { } / minByOrNull { } | element | max(xs, key=f) |
sortedBy { } / sortedByDescending | List | sorted(xs, key=f) |
any { } all { } none { } | Boolean | any(...) |
first { } / firstOrNull { } | element | next(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 / Set | set(xs) |
take(n) drop(n) | List | xs[:n] xs[n:] |
zip(ys) chunked(n) windowed(n) | List | zip |
flatMap { } | List | nested comprehension |
forEach { } | Unit | for loop |
removeAll { } / retainAll { } | Boolean (changed?) | in-place filter, MutableList only |
Scope functions (you'll see these everywhere)
| Fn | Inside, object is | Returns | Typical use |
|---|---|---|---|
let | it | lambda result | x?.let { … } null handling |
apply | this | the object | configure after creating: Person().apply { age = 3 } |
also | it | the object | side effects: .also { println(it) } |
run / with | this | lambda result | compute something from an object's members |
use | it | lambda result | auto-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.
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.
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
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.
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 class | interface | |
|---|---|---|
| State (backing fields) | yes | no (properties must be abstract or computed) |
| Constructor | yes | no |
| How many per class | one | many |
| Use for | "is-a" with shared code/state | "can-do" capability |
Type checks & casts
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 #
| Modifier | Visible to | Python / C analogue |
|---|---|---|
public (default) | everyone | normal names / header-exposed |
private | this class (or this file, if top-level) | _name convention / static in C file |
protected | this class + subclasses | — |
internal | same 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.
| Matcher | Asserts |
|---|---|
a shouldBe b / shouldNotBe | a == 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 wrote | What happens | Fix |
|---|---|---|
7 / 2 | 3 (Int division) | 7 / 2.0 or .toDouble() |
for (i in 0..n) | runs n+1 times | 0..<n / until |
val area = w * h in a class | stale if w changes | val area get() = w * h |
set(v) { prop = v } | infinite recursion → StackOverflowError | field = 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 = someInt | type mismatch | someInt.toLong() |
sqrt(2) | no Int overload | sqrt(2.0) |
map[key].length | won't compile (nullable) | map[key]?.length ?: 0 |
listOf(1).add(2) | no add on List | mutableListOf |
println(array) | [I@6d06d69c | contentToString() |
shouldBe 0.1 + 0.2 | fails on floating point | plusOrMinus |
when (x) { … } as value | "must be exhaustive" | add else |
'a' == "a" | compile error: Char vs String | pick one type |
Int.MAX_VALUE + 1 | silently negative | Long |
| printing extra output | auto-graders compare exact stdout | print 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.
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? = nullStudentAccount 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.