Kotlin JVM language and compiler
Light · Postcard
102 × 152 mm · PDF
Dark · Postcard
102 × 152 mm · PDF
Ink saver · Postcard
102 × 152 mm · PDF
Light · A4 landscape
297 × 210 mm · PDF
Dark · A4 landscape
297 × 210 mm · PDF
Ink saver · A4 landscape
297 × 210 mm · PDF
Light · A3 landscape
420 × 297 mm · PDF
Dark · A3 landscape
420 × 297 mm · PDF
Ink saver · A3 landscape
420 × 297 mm · PDF
Start here
kotlinc <file>.kt -include-runtime -d
<out>.jar
java -jar <out>.jar
kotlinc -script <file>.kts
val <name> = <value>
var <name>: <Type>
fun <name>(<p>: <T>): <R>
data class <Name>(val <p>: <T>)
<x>?.<member> ?: <default>
Concepts
- hello.kt source
- hello.jar bytecode
- JVM java -jar
- Output stdout
Compiler and runner
kotlinc <file>.kt -d <dir>
kotlinc <file>.kt -include-runtime -d
<out>.jar
java -jar <out>.jar
kotlin -classpath <out>.jar <Name>Kt
kotlinc -script <file>.kts
kotlinc -script <file>.kts -- <args>
kotlinc -Xreplkotlinc -cp <path> <file>.kt
kotlinc -version
Variables and types
val <n>: <T> = <v>
var <n> = <v>
const val <N> = <v>
"Hi $<name> ${<expr>}"
"""<text>"""
<x> as <T> / <x> as? <T>
<x> is <T>
<a>..<b> / <a> until <b>
val <n> by lazy { <init> }
Null safety
<T>?<x>?.<member>
<x> ?: <default>
<x>!!<x>?.let { <block> }
<x> ?: return
Functions and lambdas
fun <n>(<p>: <T> = <d>): <R>
{ }
fun <n>(<p>: <T>) = <expr>
<f>(<name> = <v>)
{ <x> -> <expr> }
itfun <T>.<n>(): <R>
(<A>) -> <B>
Classes and objects
class <N>(val <p>: <T>)
data class <N>(val <p>: <T>)
<obj>.copy(<p> = <v>)
val (<a>, <b>) = <obj>
object <N> { }
companion object { }
interface <N> { }
open class <N>
sealed class <N> / sealed interface <N>
enum class <N> { <A>, <B> }
Control flow
if (<c>) <a> else <b>
when (<x>) { <v> -> <r>; else ->
<d> }
when { <cond> -> <r> }
for (<i> in <range>) { }
<list>.forEachIndexed { <i>, <v> ->
}
try { } catch (e: <E>) { } finally { }
Collections
listOf(<a>, <b>)
mutableListOf(<a>)
mapOf(<k> to <v>)
setOf(<a>, <b>)
<c>.map { <expr> }
<c>.filter { <cond> }
<c>.first { <cond> } / <c>.firstOrNull {
<cond> }
<c>.groupBy { <key> }
<c>.sortedBy { <key> }
<c>.fold(<init>) { <acc>, <x> ->
}
<c>.asSequence()
<c>.joinToString(", ")
Scope functions
<x>.let { <it> -> <r> }
<x>.apply { <this> }
<x>.also { <it> }
with(<x>) { <block> }
Coroutines
suspend fun <n>()
runBlocking { <block> }
launch { <block> }
async { <expr> }.await()
delay(<ms>)
coroutineScope { <block> }
withContext(Dispatchers.IO) { }
Recipes
# hello.ktfun main() = println("Hello")kotlinc hello.kt -include-runtime -d hello.jarjava -jar hello.jar
# list.ktsjava.io.File(".").listFiles()?.forEach { println(it.name) }kotlinc -script list.kts
sealed interface Resultdata class Ok(val v: Int) : Resultdata object Fail : Resultfun show(r: Result) = when (r) { is Ok -> "ok ${r.v}" Fail -> "failed"}
val (a, b) = coroutineScope { val x = async { fetchA() } val y = async { fetchB() } x.await() to y.await()}



