Explore Kotlin values, functions, null handling and application code.

Before starting: Basic variables, functions, and a compatible JVM toolchain.

Practice project: Build a reading-list utility using null-safe data handling and tests.

1. Kotlin Foundations, Architecture & Environment

  1. Kotlin Introduction, History & The JetBrains / Google Vision
  2. Setting Up Kotlin: JDK, Kotlin CLI (kotlinc), Gradle / Maven & IntelliJ IDEA
    Read the example and try it

    Compare the compiler and JVM selected in this terminal with the versions configured for the project.

    Terminal with the Kotlin compiler and a JDK installed.

    kotlinc -version
    java -version

    Explain why running the resulting JAR still needs a JVM.

    Package a main function that prints Ready with -include-runtime.

    Expected result
    java -jar lab.jar prints Ready when a compatible JVM is installed. The JAR contains bytecode and Kotlin runtime classes, not the JVM executable.
  3. Anatomy of a Kotlin Program: Packages, Imports, Top-Level Functions & main()
    Read the example and try it

    A Kotlin console program starts at main. A helper can return a label while main handles output.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun seatLabel(n: Int) = "Seat " + n
    fun main() { println(seatLabel(7)) }

    Place an entry point in a named package.

    Put fun main() in Entry.kt under package campus. Have it print Campus.

    Expected result
    The JVM entry class is campus.EntryKt unless renamed by annotation. Invoking its main prints Campus.
  4. Variables & Immutability: val vs var, Type Inference, and Primitive Types
    Read the example and try it

    Use val for the capacity that stays fixed and var for the count that changes after a booking.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val capacity = 12
        var booked = 4
        booked++
        println(capacity - booked)
    }

    Compare adding an element with reassigning the list variable.

    Bind mutableListOf("Lab") to val rooms, then add Hall.

    Expected result
    [Lab, Hall]. Reassigning rooms to a new list is a compile error.
  5. String Templates, Multi-line Raw Strings ("""), and String Manipulation
    Read the example and try it

    Put a calculated value inside a message. Braces make the whole calculation part of the template.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val capacity = 8
        val used = 3
        println("Free seats: ${capacity - used}")
    }

    Build a two-line message containing a calculated value.

    Use two seats at 4 credits each. Print a heading and the computed price on a second line.

    Expected result
    Quote
    8 credits

2. Control Flow, Expressions & Basic Types

  1. Kotlin Type System: Numbers, Booleans, Characters & Bitwise Operations
    Read the example and try it

    Integer division drops the fractional part. Convert one operand before division when the answer needs decimals.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        println(7 / 2)
        println(7.toDouble() / 2)
    }

    Convert a count to Long before multiplication.

    Multiply 100,000 by 100,000 after converting the first operand to Long.

    Expected result
    10000000000
  2. Conditional Expressions: if and else as Expressions
    Read the example and try it

    An if expression can produce the text stored in a variable. Test both zero capacity and a positive capacity.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val left = 2
        val sign = if (left > 0) "Open" else "Full"
        println(sign)
    }

    Assign one of two fees based on a condition.

    Members pay 5, others pay 8. Check both conditions.

    Expected result
    [5, 8]
  3. Powerful Pattern Matching: The when Expression & Statement
    Read the example and try it

    A when expression chooses the first matching branch. Include a fallback for unfamiliar ticket labels.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun fare(kind: String) = when (kind) {
        "child" -> 3
        "adult" -> 6
        else -> 0
    }
    
    fun main() {
        println(fare("adult"))
        println(fare("other"))
    }

    Map all values of a small enum to labels.

    Define Open and Closed. Use an exhaustive when that returns open or closed.

    Expected result
    [open, closed]
  4. Range Expressions (.., until, downTo, step) and Range Checking (in)
    Read the example and try it

    A progression can skip every other seat. The inclusive upper bound appears only if the step reaches it.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        println((2..9 step 2).toList())
    }

    Compare an inclusive range with a half-open range.

    Compare 1..4 with 1 until 4.

    Expected result
    [1, 2, 3, 4] [1, 2, 3]
  5. Loops & Iterations: for Loops, while, do-while, and Loop Labels
    Read the example and try it

    A labelled break can exit the outer loop immediately after finding a matching position.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        outer@ for (row in 1..3) {
            for (seat in 1..4) {
                if (row == 2 && seat == 3) break@outer
                println("$row-$seat")
            }
        }
    }

    Trace two nested loops with one labeled break.

    Loop row 1..2, column 1..3. Stop both loops before processing (1,3).

    Expected result
    [(1, 1), (1, 2)]

3. Functions, Lambdas & Functional Programming

  1. Functions: Parameters, Named Arguments & Default Parameter Values
    Read the example and try it

    Call a function with its default fare or override it by name. The parameter names make the second call easier to read.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun bill(seats: Int, fare: Int = 4) = seats * fare
    
    fun main() {
        println(bill(3))
        println(bill(fare = 5, seats = 3))
    }

    Call a function once with defaults and once with a named override.

    Define price(count=2,rate=4). Call with no arguments and with rate=5.

    Expected result
    8 10
  2. Single-Expression Functions and Variable Number of Arguments (vararg, Spread Operator *)
    Read the example and try it

    A vararg accepts individual numbers. The spread operator passes the contents of an existing integer array.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun total(vararg marks: Int) = marks.sum()
    
    fun main() {
        val marks = intArrayOf(4, 8)
        println(total(*marks))
    }

    Call one vararg function with three literals and then an array.

    Sum 2,3,5 once as literals and once from intArrayOf(2,3,5).

    Expected result
    10 10
  3. Extension Functions & Extension Properties: Extending Classes Without Inheritance
    Read the example and try it

    An extension adds call syntax to a type without changing its class definition. This one trims a pasted route label.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun String.routeLabel() = trim().uppercase()
    
    fun main() {
        println("  east ".routeLabel())
    }

    Compare extension resolution for a base-typed reference.

    Define extensions label() on Base and Child. Assign Child() to a Base variable.

    Expected result
    base — extension selection uses the declared receiver type.
  4. Higher-Order Functions, Lambda Expressions & Trailing Lambda Syntax
    Read the example and try it

    A higher-order function accepts a rule as an argument. Keep the fares that satisfy the supplied predicate.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val fares = listOf(2, 6, 9)
        println(fares.filter { it >= 5 })
    }

    Rewrite one call using trailing-lambda syntax.

    Keep even values from 1,2,3,4 using filter with a trailing lambda.

    Expected result
    [2, 4]
  5. Inlining Mechanics: inline, noinline, and crossinline for Zero-Overhead Lambdas
    Read the example and try it

    Inlining lets a small higher-order function expand a call at the use site. Keep the rule readable and measure critical paths.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    inline fun twice(action: () -> Unit) { action(); action() }
    fun main() { twice { println("check") } }

    Explain why a callback stored for later may need noinline.

    Pass a callback to an inline function that returns that callback for later.

    Expected result
    Mark that callback noinline. Invoking the returned callback later still produces its value; an ordinary inline parameter cannot simply escape this way.

4. Null Safety, Type Checking & Defensive Coding

  1. The Billion-Dollar Mistake Solved: Nullable Types (T?) vs Non-Nullable Types (T)
    Read the example and try it

    A nullable declaration admits both text and null. Check it before reading a property that requires a real string.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val nickname: String? = null
        if (nickname != null) println(nickname.length) else println("No nickname")
    }

    Compare the types of a required and an optional label.

    Declare a String containing Lab and a String? initialized to null.

    Expected result
    Lab null. Only the nullable declaration accepts a later null assignment if the binding is mutable.
  2. Safe Call Operator (?.) and The Elvis Operator (?:)
    Read the example and try it

    Safe access passes null along. The Elvis operator supplies a useful default for the display.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun displayLength(name: String?) = name?.length ?: 0
    
    fun main() {
        println(displayLength(null))
    }

    Test a missing string and an empty string with the same fallback.

    Apply the fallback "unknown" to null and to an empty string. Display the results in brackets.

    Expected result
    [unknown][]
  3. Not-Null Assertion Operator (!!) and Dealing with Legacy Java Nulls
    Read the example and try it

    A non-null assertion can fail at runtime. Use an explicit validation step at the input boundary when a value is required.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun readSeat(raw: String?): Int {
        return requireNotNull(raw?.toIntOrNull()) { "Enter a seat number" }
    }
    
    fun main() {
        println(runCatching { readSeat("A4") }.isFailure)
    }

    Replace an unsafe assertion with explicit missing-value handling.

    Replace !! with a safe length lookup returning 0 if the label is absent.

    Expected result
    0 3 — lengths for null and Lab.
  4. Type Checks and Smart Casts (is, !is) & Explicit Casts (as, as?)
    Read the example and try it

    A type test can narrow a value for the current branch. Unknown input types take the fallback path safely.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun width(value: Any) = if (value is String) value.length else 0
    
    fun main() {
        println(width(7))
    }

    Try casting a text value to an integer type.

    Assign "7" to Any and use as? Int.

    Expected result
    null — a cast is different from parsing the string.
  5. Safe Standard Scope Functions: let, run, with, apply, and also
    Read the example and try it

    apply is useful for configuring a fresh object because it returns that object. The StringBuilder is still available afterwards.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val label = StringBuilder().apply { append("Gate "); append(4) }
        println(label.toString())
    }

    Configure a builder and keep the builder as the result.

    Use StringBuilder().apply to append Lab and a hyphen followed by 2.

    Expected result
    Lab-2 — apply returns the builder.

5. Object-Oriented Kotlin: Classes, Interfaces & Inheritance

  1. Classes, Primary & Secondary Constructors, and init Blocks
    Read the example and try it

    Validate constructor inputs in init so an invalid object cannot escape from construction.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    class Room(val seats: Int) { init { require(seats >= 0) } }
    fun main() { println(Room(4).seats) }

    Trace two initializers and one init block.

    Declare property A, an init block, then property B. Log each initialization.

    Expected result
    A init B
  2. Properties, Custom Getters/Setters, and Backing Fields (field)
    Read the example and try it

    Use the backing field inside a setter to store the validated value. Assigning through the property there would call the setter again.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    class Counter {
        var seats = 0
            set(value) { require(value >= 0); field = value }
    }
    
    fun main() {
        val counter = Counter()
        println(runCatching { counter.seats = -1 }.isFailure)
    }

    Write a setter that clamps a negative count to zero.

    Set a count to −2, then to 5. Clamp at zero inside the setter.

    Expected result
    0 5
  3. Inheritance, Open Classes, Method Overriding (open, override) & Final by Default
    Read the example and try it

    A subclass can change a method marked open. Calls through the base type still use the actual object's implementation.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    open class Ticket { open fun fare() = 4 }
    class ReturnTicket : Ticket() { override fun fare() = 2 * super.fare() }
    
    fun main() {
        val ticket: Ticket = ReturnTicket()
        println(ticket.fare())
    }

    Create an open base method and override it.

    A base method returns space. A child overrides it to return lab. Call through the base type.

    Expected result
    lab
  4. Abstract Classes and Interfaces: Multiple Interface Implementation & Default Methods
    Read the example and try it

    An interface defines a behaviour and can supply a default method that uses it. Implementations still choose their own label.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    interface Labelled { fun label(): String; fun show() = println(label()) }
    class Gate : Labelled { override fun label() = "East" }
    
    fun main() {
        Gate().show()
    }

    Give a class one abstract base and two capabilities.

    Implement Bookable and Named on a Lab subclass of an abstract Space.

    Expected result
    The concrete Lab can be used as Space, Bookable or Named. For name Lab and reserve() returning true, the result is Lab true.
  5. Visibility Modifiers: public, private, protected, and internal (Module-level)
    Read the example and try it

    Restrict the setter so only methods on the object can change the count. Callers can still inspect it.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    class Stock {
        var left = 2
            private set
        fun take() { if (left > 0) left-- }
    }
    
    fun main() {
        val stock = Stock()
        repeat(3) { stock.take() }
        println(stock.left)
    }

    Compare private and internal access in a small module.

    Declare a private class member secret and an internal helper in the same module.

    Expected result
    Another file in the module may call the internal helper, but an unrelated class cannot read the private member. Verify the failing access separately from the compiling example.

6. Advanced OOP, Data Modeling & Delegation

  1. Data Classes: copy(), componentN() Destructuring & Auto-Generated equals/hashCode/toString
    Read the example and try it

    copy produces a new data object with selected changes. The first ticket still has its original seat.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    data class Ticket(val id: Int, val seat: Int)
    
    fun main() {
        val first = Ticket(8, 3)
        println(first.copy(seat = 4))
    }

    Copy a data class and mutate a shared list.

    Copy a data class holding a mutable list ["Lab"], then add Hall through the copy.

    Expected result
    [Lab, Hall] [Lab, Hall]
  2. Sealed Classes and Sealed Interfaces: Exhaustive Pattern Matching Without else
    Read the example and try it

    A sealed hierarchy describes a known set of outcomes. A when expression can cover them all without a catch-all branch.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    sealed interface Result
    data class Booked(val seat: Int) : Result
    object Full : Result
    fun label(r: Result) = when (r) { is Booked -> "Seat " + r.seat; Full -> "Full" }
    
    fun main() {
        println(label(Booked(8)))
        println(label(Full))
    }

    Handle success and failure without a catch-all branch.

    Model success and failure as a sealed result and handle both in when.

    Expected result
    Success(3) → 3 seats. Failure → unavailable. Adding a new alternative requires handling it in an exhaustive expression.
  3. Nested and Inner Classes (inner), Enum Classes with Properties & Methods
    Read the example and try it

    An inner object can read its surrounding instance. Another coach can have a different prefix for the same seat number.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    class Coach(val prefix: String) {
        inner class Seat(val n: Int) { fun label() = prefix + n }
    }
    
    fun main() {
        println(Coach("B").Seat(4).label())
    }

    Compare a nested helper with an inner iterator.

    Give Outer the value 8 and make an inner helper read it directly.

    Expected result
    The inner helper returns 8. An ordinary nested helper needs an explicit Outer reference to read that instance's value.
  4. Object Declarations, Singletons, Companion Objects & Factory Patterns
    Read the example and try it

    A companion can offer a named constructor. This factory normalises the label before creating the ticket.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    class Pass private constructor(val zone: String) {
        companion object { fun forZone(raw: String) = Pass(raw.trim()) }
    }
    
    fun main() {
        println(Pass.forZone(" East ").zone)
    }

    Give shared configuration an object declaration.

    Read the same object declaration from two variables and compare identity.

    Expected result
    true
  5. Property Delegation: by lazy, Delegates.observable(), and Custom Delegates
    Read the example and try it

    A lazy property runs its initializer on first access. Subsequent reads of the same property reuse that result.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val heading: String by lazy { println("Building"); "Room board" }
        println(heading)
        println(heading)
    }

    Count initializer calls across two reads.

    Increment a counter inside lazy, and read the value twice.

    Expected result
    7 7 1 — the initializer ran once.

7. Collections, Sequences & Generics

  1. Kotlin Collections Hierarchy: Read-Only vs Mutable Collections
    Read the example and try it

    A read-only view exposes a narrower set of operations. If the underlying mutable list changes, the view can reflect the change.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        val edit = mutableListOf("A")
        val view: List<String> = edit
        edit.add("B")
        println(view)
    }

    Observe a mutable list through a read-only reference.

    Use a List reference backed by mutableListOf(1); append 2 via the mutable reference.

    Expected result
    [1, 2]
  2. Functional Collection Transformations: map, filter, flatMap, reduce, fold, groupBy
    Read the example and try it

    Filter before transforming to avoid including cancelled items. Sum the remaining adjusted fares.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        println(listOf(0, 3, 5).filter { it > 0 }.map { it * 2 }.sum())
    }

    Filter positive values and fold them into a sum.

    Keep positives from [−2,3,4] and sum from zero.

    Expected result
    7
  3. Lazy Evaluation with Sequences (Sequence<T>): Memory Optimization
    Read the example and try it

    A sequence performs work as values are requested. take can stop a search after the first two qualifying values.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun main() {
        println((1..100).asSequence().filter { it % 7 == 0 }.take(2).toList())
    }

    Trace how many elements are visited before first().

    Filter a sequence of 1,2,3,4 for even numbers, then call first. Count inspected inputs.

    Expected result
    2 2 — result 2 after examining two values.
  4. Generics: Type Parameters, Generic Classes & Functions, and Type Constraints
    Read the example and try it

    Constrain a generic value to a type that can compare itself. Then the same function works for numbers and names.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    fun <T : Comparable<T>> larger(a: T, b: T): T = if (a >= b) a else b
    
    fun main() {
        println(larger(3,8))
        println(larger("A","B"))
    }

    Write a maximum function that accepts comparable types.

    Call a generic maximum function for 3,7 and for A,B.

    Expected result
    7 B
  5. Advanced Variance: Declaration-Site Variance (out, in) & Star Projection (*)
    Read the example and try it

    An out parameter can safely supply values through a broader type. This interface only produces an item.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    interface Source<out T> { fun next(): T }
    fun readAny(source: Source<Any>): Any = source.next()
    
    fun main() {
        val source = object : Source<String> { override fun next() = "East" }
        println(readAny(source))
    }

    Assign a producer of strings to a compatible broader producer.

    Assign a Source<String> to a Source<Any> using a covariant producer.

    Expected result
    Lab — the broader reference can safely read the produced string.

8. Asynchronous Kotlin: Coroutines & Structured Concurrency

  1. Coroutines Architecture: Light-Weight Threads, Suspending Functions (suspend) & Continuation
    Read the example and try it

    A suspending delay allows other coroutine work to proceed while waiting. Call this function from a coroutine.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun arrival(): String {
        kotlinx.coroutines.delay(20)
        return "Arrived"
    }
    
    fun main() {
        runBlocking { println(arrival()) }
    }

    Separate suspension from choosing a dispatcher.

    A suspending function runs its body without switching dispatcher or suspending.

    Expected result
    Its code can execute on the caller's thread. A suspend declaration permits suspension; it does not automatically send work to a background thread.
  2. Coroutine Builders: launch, async, runBlocking, and Deferred<T>.await()
    Read the example and try it

    async provides a Deferred from which the caller can obtain the result. Launch is useful for work that just needs completion.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun total() = coroutineScope {
        val first = async { 3 }
        val second = async { 5 }
        first.await() + second.await()
    }
    
    fun main() {
        runBlocking { println(total()) }
    }

    Start two value-producing tasks and await their results.

    Start two async tasks returning 2 and 3 and await their results.

    Expected result
    5
  3. Coroutine Context & Dispatchers: Dispatchers.Default, IO, Main, and Unconfined
    Read the example and try it

    Move blocking file I/O to an appropriate dispatcher. The caller resumes with the file contents after completion.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun label(file: java.io.File) = withContext(Dispatchers.IO) { file.readText() }
    
    fun main() {
        runBlocking {
            val path = java.nio.file.Files.createTempFile("seat", ".txt").toFile()
            try { path.writeText("East"); println(label(path)) } finally { path.delete() }
        }
    }

    Move blocking work to an appropriate dispatcher.

    Use withContext(Dispatchers.IO) for a blocking read of a temporary file containing Lab.

    Expected result
    Lab — the result returns to the caller's coroutine context. No particular thread name is guaranteed.
  4. Structured Concurrency, CoroutineScope, Job Lifecycles & Cancellation Handling
    Read the example and try it

    A structured scope owns its children. Cancelling the job prevents the delayed message and join waits for termination.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun inspect() = coroutineScope {
        val job = launch { delay(1000); println("late") }
        job.cancelAndJoin()
    }
    
    fun main() {
        runBlocking { inspect() }
    }

    Trace a parent and two cooperative child tasks.

    Launch two cooperative children in one parent; cancel and join the parent.

    Expected result
    Both children are canceled and the parent's join completes. The order of child cleanup is not guaranteed.
  5. Exception Handling in Coroutines: CoroutineExceptionHandler & SupervisorJob
    Read the example and try it

    A supervised scope lets independent children have separate failure paths. Await the failing child and handle its expected exception.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun check() = supervisorScope {
        val job = async<Int> { error("Missing room") }
        try { job.await() } catch (e: IllegalStateException) { println(e.message) }
    }
    
    fun main() {
        runBlocking { check() }
    }

    Model two siblings where one fails and the other continues.

    In supervisorScope, one async child fails and the other returns 7. Observe the failure using await.

    Expected result
    failed 7 — the sibling supplies its result.

9. Reactive Streams: Kotlin Flow & Channels

  1. Cold Asynchronous Streams: Kotlin Flow<T>, flow { } Builder & Terminal Operators (collect)
    Read the example and try it

    A cold flow runs its builder for each collection. No seats are emitted until a collector starts.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    val seats = flow { emit(3); emit(7) }
    suspend fun show() { seats.collect { println(it) } }
    
    fun main() {
        runBlocking { show(); show() }
    }

    Collect the same cold flow twice and trace producer starts.

    Collect a cold flow emitting 4 twice and count producer starts.

    Expected result
    [4] [4] 2
  2. Flow Transformations & Operators: map, filter, transform, take, zip, combine
    Read the example and try it

    zip pairs one value from each flow in order. It stops when one input runs out.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    val fares = flowOf(3, 5)
    val counts = flowOf(2, 4)
    val bills = fares.zip(counts) { price, qty -> price * qty }
    
    fun main() {
        runBlocking { bills.collect { println(it) } }
    }

    Compare streams of different lengths using zip and combine.

    Let the left stream emit A and B, and the right emit 1 only. For combine, ensure 1 is present before B and both combinations are observed.

    Expected result
    zip yields A1 only. Under the stated ordering combine can yield A1 then B1. Without controlling timing, intermediate combinations can be skipped.
  3. Flow Context & Buffering: flowOn(Dispatchers.IO), buffer(), and conflate()
    Read the example and try it

    buffer can let a producer get ahead of a slower collector. Values remain in order while the buffer has space.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun showSeats() {
        (1..3).asFlow().buffer(1).collect { delay(5); println(it) }
    }
    
    fun main() {
        runBlocking { showSeats() }
    }

    Trace a slow display that only needs the newest reading.

    The display is busy with value 1 while values 2 and 3 arrive on a conflated stream.

    Expected result
    If both arrive before the display requests again, it next sees 3. Intermediate value 2 need not appear. Do not require a fixed sequence without synchronizing the test.
  4. Hot Streams: StateFlow (State Holder) vs SharedFlow (Event Bus) in Production
    Read the example and try it

    A StateFlow keeps a current value that a late reader can inspect. Update it when a new count arrives.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    fun main() {
        val seats = MutableStateFlow(3)
        seats.value = 2
        println(seats.value)
    }

    Choose streams for current screen state and transient events.

    A screen needs its current room, plus one-time toast messages for active collectors.

    Expected result
    StateFlow retains the current room for a new collector. SharedFlow with replay=0 can deliver new toasts to active collectors without replaying old ones.
  5. Concurrency Pipelines with Channels: Channel<T>, produce, consumeEach
    Read the example and try it

    A channel transfers values from a sender to a receiver. Closing it allows the receiver's loop to finish.

    Kotlin/JVM console program with kotlinx-coroutines-core on the classpath.

    import kotlinx.coroutines.*
    import kotlinx.coroutines.flow.*
    import kotlinx.coroutines.channels.Channel
    
    suspend fun tickets() = coroutineScope {
        val channel = Channel<Int>()
        launch { channel.send(7); channel.close() }
        for (seat in channel) println(seat)
    }
    
    fun main() {
        runBlocking { tickets() }
    }

    Draw three jobs moving through two consumers.

    Send jobs 1,2,3 into a channel and close it. Start two ordinary consuming workers.

    Expected result
    Across both workers the collected jobs are [1,2,3] after sorting. Which worker gets each job can vary.

10. Modern Ecosystem, Testing, Multiplatform & Android

  1. Kotlin Reflection & Annotations: @Target, @Retention, and Runtime Introspection
    Read the example and try it

    A class reference exposes runtime type information. Some advanced reflection features require the kotlin-reflect dependency.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    data class Gate(val id: Int)
    
    fun main() {
        println(Gate::class.simpleName)
    }

    Decide which annotation retention a runtime inspector needs.

    An annotation is read via Java reflection on the JVM.

    Expected result
    Use RUNTIME retention and an appropriate target. The reflection call sees the annotation; SOURCE-retained metadata is absent.
  2. Interoperability with Java: Calling Kotlin from Java (@JvmStatic, @JvmOverloads, @file:JvmName)
    Read the example and try it

    JvmStatic exposes a convenient static entry point to Java callers. Here Java can call Seats.open directly.

    Kotlin/JVM console program. Save as Main.kt and run the main function.

    object Seats { @JvmStatic fun open(n: Int): Boolean = n > 0 }
    
    fun main() {
        println(Seats.open(0))
    }

    Show how a Java caller can omit a defaulted trailing argument.

    Expose fee(count:Int, rate:Int=4) with @JvmOverloads and call fee(3) from Java.

    Expected result
    12; Java can call the generated one-argument overload. Without the generated overload, ordinary Java code must supply rate.
  3. Unit Testing with Kotlin: kotlin.test, JUnit 5, MockK & Assertions
    Read the example and try it

    Test the exact boundary as well as its neighbours. This JUnit test treats zero seats as full.

    Kotlin/JVM test source with JUnit Jupiter on the test classpath.

    import org.junit.jupiter.api.Assertions.assertFalse
    import org.junit.jupiter.api.Assertions.assertTrue
    import org.junit.jupiter.api.Test
    
    class SeatTest {
        private fun canReserve(left: Int) = left > 0
    
        @Test fun checkBoundary() {
            assertFalse(canReserve(0))
            assertTrue(canReserve(1))
        }
    }

    Test a boundary input and check the returned value.

    Test a function accepting counts 1 through 6 at the adjacent boundary values 0 and 1.

    Expected result
    false true
  4. Kotlin Serialization: kotlinx.serialization with JSON, Data Encoding & Polymorphic Objects
    Read the example and try it

    A serializer can apply defaults when an optional field is omitted. This fragment needs the kotlinx.serialization plugin and JSON library.

    Kotlin project with the serialization compiler plugin and kotlinx-serialization-json installed.

    import kotlinx.serialization.Serializable
    import kotlinx.serialization.json.Json
    
    @Serializable data class Room(val label: String, val seats: Int = 0)
    fun main() {
        val room = Json.decodeFromString<Room>("""{"label":"Lab"}""")
        println(room.seats)
    }

    Round-trip a small data class and check its fields.

    Round-trip a serializable Room(name="Lab", seats=8) through JSON.

    Expected result
    The decoded object equals the original. Check the name and seat count; JSON whitespace and property order are not part of the result.
  5. Kotlin Multiplatform (KMP) & Jetpack Compose: The Future of Cross-Platform
    Read the example and try it

    Keep calculations that need no platform API in commonMain. Both Android and desktop callers can reuse the same rule.

    Place remaining in commonMain. The main function shows a console caller.

    fun remaining(capacity: Int, booked: Int): Int {
        require(booked in 0..capacity)
        return capacity - booked
    }
    
    fun main() {
        println(remaining(4, 3))
    }

    Separate shared price calculation from platform-specific display code.

    A price of 4 credits per seat is shared by Android and iOS; the platform-specific view displays the result.

    Expected result
    Three seats cost 12 in common code on both targets. Native UI code belongs in its platform source set. A JVM-only run checks the calculation, not an iOS or Android build.

Trace changing state and check loop boundaries

A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.

Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.

PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
    total ← total + value
RETURN total
Check the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.

Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.

Make a small learning project reproducible

A project is reproducible when another learner can obtain the same inputs, install the required tools, and repeat your checks. Record the tool versions and exact run commands. Use synthetic or permission-cleared sample data. Keep credentials outside the repository. A successful run on your laptop is a starting point; a fresh environment is a better check.

Any language; choose the package and build tools appropriate to that course

study-project/
  README.md          # setup, run, test, expected result
  src/               # your implementation
  tests/             # behavior checks
  data/              # small synthetic example data
  .gitignore         # caches, build output, local secrets
Check the output
This is a suggested directory layout, not a command to execute. Adapt conventions to the chosen language.

Build a score summarizer. Include an empty-input test, a malformed-input test, and one example whose answer can be calculated by hand.

Open the Kotlin learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.