kotlinx
- Kotlin course
- Intermediate
- Lesson 104/116
- 5 min
Learn kotlinx libraries.
kotlinx: Kotlin extension libraries
kotlinx is the namespace of Kotlin's official extension libraries. They provide capabilities beyond the standard library that are often needed. The best known are kotlinx-coroutines-core (async programming), kotlinx-serialization-json (JSON processing) and kotlinx-datetime (date and time).
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*To use these libraries you first add them as a dependency in build.gradle.kts. Then import brings the types into the file. The kotlinx packages are updated in parallel with Kotlin's release rhythm; keeping version numbers compatible matters.
Common kotlinx libraries
Some common kotlinx libraries: kotlinx-coroutines-core for coroutines and Flow, kotlinx-serialization-json for JSON conversion, kotlinx-datetime for date and time. Each is a separate dependency; adding only what you need keeps compile time short.
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
delay(100)
println("ready")
}Here delay and runBlocking are imported from kotlinx.coroutines. Each dependency version must be compatible with the Kotlin version; mismatched versions cause compile errors. Version catalogs are a common tool to manage this compatibility.
Practice Use kotlinx.coroutines
At the top of the file add import kotlinx.coroutines.*. Write main as fun main() = runBlocking { ... }. Inside it call println("Ready"). runBlocking comes from kotlinx.coroutines.
Starter code
// wildcard import the kotlinx.coroutines library
// main: inside runBlocking, println "Ready"Sample solution
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Ready")
}Expected output
Ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is a kotlinx library?
- kotlin.test
- java.util.List
- kotlinx-coroutines-core Correct answer
- javax.swing
Explanation: kotlinx-coroutines-core is the kotlinx library for async programming.
2 Import kotlinx
import ____.coroutines.*
import kotlinx.coroutines.*
Explanation: import kotlinx.coroutines.* brings the coroutines library in.
3 Match the kotlinx libraries
| Term | Meaning |
|---|---|
kotlinx-coroutines-core |
Async programming |
kotlinx-serialization-json |
JSON conversion |
kotlinx-datetime |
Date and time |
kotlinx.coroutines.flow |
Flow streams |