πŸŽ“ A1Learner
πŸ”
0 of 28 lessons completed

Kotlin Advanced Introduction

Kotlin Advanced is the third band of Kotlin courses. It goes deep on coroutines, generics, delegation, and code that builds code.

A data class for a topic

Topic is a data class with a name and a lesson count. main builds one topic and prints its two properties.

data class Topic(val name: String, val lessons: Int)

fun main() {
    val topic = Topic("Coroutines", 9)
    println(topic.name)
    println(topic.lessons)
}

A list of topics

The list holds three topic names in order. forEach prints each name on its own line.

fun main() {
    val topics = listOf("Coroutines", "Generics", "Delegation")
    topics.forEach { println(it) }
}

Filtering a list of plans

Each plan is a data class value with a title and a length in minutes. filter keeps the plans of five minutes or more, and the loop prints their titles.

data class LessonPlan(val title: String, val minutes: Int)

fun main() {
    val plans = listOf(LessonPlan("Coroutines", 5), LessonPlan("Generics", 6), LessonPlan("Delegation", 4))
    val long = plans.filter { it.minutes >= 5 }
    for (plan in long) {
        println(plan.title)
    }
}

Example

data class Module(val name: String, val lessons: Int)

fun main() {
    val modules = listOf(
        Module("Coroutines", 9),
        Module("Generics", 4),
        Module("Delegation", 3)
    )
    var total = 0
    for (module in modules) {
        println("${module.name}: ${module.lessons}")
        total = total + module.lessons
    }
    println("Total: $total")
}

Key points

  • Coroutines and Flow handle work that waits and values that arrive over time.
  • Generics go deeper with reified types, variance, and projections.
  • Delegation hands work to another object, and DSL building shapes code into small builders.
  • A taste of reflection reads simple type information from values while a program runs.
  • Context parameters let a function receive shared values from the code around its call.
  • Coroutines are not part of the standard library, and they live in the kotlinx.coroutines library.
  • The kotlinx.coroutines library ships with the Kotlin toolchain, and lessons that use it carry its import line.

In this example, the list holds three Module values. The loop prints each module with its lesson count and adds the count to the total. The last line prints the total of 16.

Note

Every other example in this course uses only the standard library.

Try it Yourself

Edit the code, then press Run.

Running is simulated Β· Kotlin Playground

Exercise

Where do coroutines live in Kotlin?