Kotlin: reference

A modern language for Android and the server: concise syntax, null safety and coroutines.

Program structure

Minimal program

Execution starts in the main function. println prints a line and moves to a new one. A semicolon at the end of a line is not needed.

fun main() {
    println("Hello, world!")
}

Build and run

The commands run in a terminal. kotlinc is the compiler and java -jar runs the built file. Gradle is more convenient for larger projects.

kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar

./gradlew run        # if the project uses Gradle

Variables and types

val and var

val is an immutable value and var is a variable. The type is usually inferred, but you can state it after a colon.

val name = "Olena"
var score = 0
score += 10
val age: Int = 16
println("$name $score $age")

Basic types

Main types: Int, Long, Double, Float, Boolean, Char. Add L for Long and f for Float; underscores separate digit groups.

val i: Int = 42
val big: Long = 10_000_000_000L
val d: Double = 3.14
val f: Float = 2.5f
val b: Boolean = true
val c: Char = 'a'

Type conversion

There are no implicit conversions between numbers: use toDouble, toInt and so on. toIntOrNull returns null instead of an error.

val x = 7
val y = x.toDouble() / 2
val n = "12".toInt()
val m = "abc".toIntOrNull()
println("$y $n $m")

Strings

String templates

$name inserts a variable into a string, and ${expression} evaluates an arbitrary expression inside the string.

val name = "Kotlin"
val a = 3
val b = 4
println("Hello, $name!")
println("Sum: ${a + b}")

String methods

Strings are immutable: methods return a new string. length is a property, so there are no parentheses after it.

val s = "Hello, World"
println(s.length)
println(s.uppercase())
println(s.substring(0, 5))
println(s.replace("World", "Kotlin"))
println(s.contains("World"))
println(s.split(", "))

Multiline strings

Triple quotes let you write text over several lines without escaping, and trimIndent removes the common indentation.

val text = """
    Line one
    Line two
""".trimIndent()
println(text)

Conditions

if as an expression

In Kotlin if returns a value, so there is no separate ternary operator. The last branch must be else if the result is stored.

val age = 16
if (age < 12) println("child")
else if (age < 18) println("teen")
else println("adult")

val status = if (age >= 18) "adult" else "minor"
println(status)

when

when replaces switch: branches do not fall through, break is not needed, and the result can be assigned to a variable.

val day = 6
val kind = when (day) {
    1, 2, 3, 4, 5 -> "weekday"
    6, 7 -> "weekend"
    else -> "unknown"
}
println(kind)

when with ranges and types

when without an argument checks arbitrary conditions. Branches with in check a range, and with is check the type of the value.

fun grade(n: Int) = when {
    n >= 90 -> "A"
    n in 50..89 -> "B"
    else -> "F"
}

fun kind(x: Any) = when (x) {
    is Int -> "int"
    is String -> "string"
    else -> "other"
}

Loops

for and ranges

1..3 includes both ends, until excludes the right one. downTo counts down and step sets the step.

for (i in 1..3) println(i)
for (i in 3 downTo 1) println(i)
for (i in 0 until 10 step 2) println(i)
for (ch in "abc") println(ch)

Indexes and elements

withIndex gives pairs of index and element, and indices gives only the range of collection indexes.

val items = listOf("a", "b", "c")
for (item in items) println(item)
for ((i, v) in items.withIndex()) println("$i: $v")
for (i in items.indices) println(i)

while, break and continue

continue goes to the next iteration and break leaves the loop. There is also do { } while (condition).

var n = 3
while (n > 0) {
    println(n)
    n--
}
for (i in 1..10) {
    if (i % 2 == 0) continue
    if (i > 7) break
    println(i)
}

Functions

Declaration

Parameter types are written after the name. A single-expression function can be shortened to = expression, and Unit as the result type can be omitted.

fun add(a: Int, b: Int): Int {
    return a + b
}

fun square(x: Int) = x * x

fun hello() {
    println("hi")
}

Named and default arguments

Parameters can have default values, and arguments can be passed by name in any order.

fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"

println(greet("Olena"))
println(greet("Olena", greeting = "Hi"))
println(greet(greeting = "Hey", name = "Max"))

vararg

vararg accepts a variable number of arguments. An array is passed to such a parameter with the * operator.

fun sum(vararg nums: Int): Int = nums.sum()

println(sum(1, 2, 3))
val arr = intArrayOf(4, 5)
println(sum(*arr))

Lambdas

Lambda and map, filter

A lambda is written in curly braces, and its single parameter is called it. map transforms, filter selects, fold folds.

val double = { x: Int -> x * 2 }
println(double(5))

val nums = listOf(1, 2, 3, 4)
println(nums.map { it * 2 })
println(nums.filter { it % 2 == 0 })
println(nums.fold(0) { acc, x -> acc + x })

Function as a parameter

A function type is written as (Int) -> Int. If the lambda is the last argument, it is moved outside the parentheses.

fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))

println(applyTwice(3) { it + 1 })
println(applyTwice(3, { it * 2 }))

Collections

List

listOf creates an immutable list and mutableListOf a mutable one. Access an element by index: list[0].

val list = listOf(3, 1, 2)
println(list[0])
println(list.size)
println(list.sorted())

val mutable = mutableListOf(1, 2)
mutable.add(3)
mutable.removeAt(0)
println(mutable)

Map and Set

A pair is created with to. Accessing a missing key gives null. Set stores only unique elements.

val ages = mapOf("Olena" to 16, "Max" to 17)
println(ages["Olena"])
for ((name, age) in ages) println("$name: $age")

val m = mutableMapOf<String, Int>()
m["a"] = 1
println(m)
println(setOf(1, 2, 2, 3))

Useful methods

any and all check a condition for the elements, and joinToString joins the elements into one string with a separator.

val nums = listOf(5, 3, 8, 1)
println(nums.sorted())
println(nums.max())
println(nums.any { it > 7 })
println(nums.all { it > 0 })
println(nums.first())
println(nums.joinToString(", "))

Classes

Class

Properties are declared right in the class header with val or var. Kotlin has no new keyword.

class Person(val name: String, var age: Int) {
    fun greet() = "I am $name"
}

val p = Person("Olena", 16)
p.age += 1
println(p.greet())
println(p.age)

data class

data class generates toString, equals and copy for you. An object can be split into parts: val (x, y) = a.

data class Point(val x: Int, val y: Int)

val a = Point(1, 2)
val b = a.copy(y = 5)
println(a)
println(b)
println(a == Point(1, 2))
val (x, y) = a

Interface and inheritance

Classes are closed by default: to inherit you need open. Overrides are marked with override.

interface Animal {
    fun sound(): String
}

open class Base {
    open fun hi() = "base"
}

class Dog : Animal, Base() {
    override fun sound() = "Woof"
    override fun hi() = "dog"
}

enum and object

enum class defines a set of constants and entries returns them as a list. object is a class with a single instance (a singleton).

enum class Color { RED, GREEN, BLUE }

object Config {
    const val VERSION = 1
}

println(Color.GREEN)
println(Color.entries.size)
println(Config.VERSION)

Null safety

Nullable types

A type with ? can be null. ?. calls a method safely, and ?: (the Elvis operator) gives a default value.

var name: String? = null
println(name?.length)
println(name ?: "unknown")
name = "Kotlin"
println(name?.length)

let and !!

?.let { } runs the block only if the value is not null. After a != null check the type becomes regular. !! throws an error for null.

val text: String? = "abc"
text?.let { println(it.uppercase()) }
if (text != null) println(text.length)

val n: Int? = "12".toIntOrNull()
println(n!! + 1)

Errors

try, catch, finally

The finally block always runs. Kotlin does not require declaring exceptions in a function signature: there are no checked exceptions.

try {
    val n = "abc".toInt()
    println(n)
} catch (e: NumberFormatException) {
    println("not a number")
} finally {
    println("done")
}

throw and require

throw throws an exception and require checks an argument and throws IllegalArgumentException. Custom exceptions extend Exception.

class MyError(message: String) : Exception(message)

fun checkAge(age: Int) {
    require(age >= 0) { "age < 0" }
    if (age > 150) throw MyError("too big")
    println(age)
}

try as an expression

try returns the value of the last expression of its block. runCatching wraps an error into a result, and getOrDefault gives a fallback value.

val n = try {
    "12".toInt()
} catch (e: NumberFormatException) {
    0
}
println(n)

val m = runCatching { "x".toInt() }.getOrDefault(-1)
println(m)

Extensions and scope functions

Extension functions

An extension function adds a method to an existing type without inheritance. Inside it this is the object it is called on.

fun String.shout() = this.uppercase() + "!"

val Int.isEven: Boolean
    get() = this % 2 == 0

println("hi".shout())
println(4.isEven)

let and apply

let passes the object as it and returns the lambda result. apply configures the object via this and returns the object itself.

val len = "hello".let { it.length }
println(len)

val sb = StringBuilder().apply {
    append("a")
    append("b")
}
println(sb)

Coroutines

runBlocking and launch

The kotlinx-coroutines-core library is required. launch starts a coroutine and delay suspends it without blocking the thread.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(100)
        println("world")
    }
    println("Hello")
}

suspend and async

A suspend function can only be called from a coroutine. async runs a task in parallel and await waits for the result.

import kotlinx.coroutines.*

suspend fun slow(x: Int): Int {
    delay(100)
    return x * 2
}

fun main() = runBlocking {
    val a = async { slow(1) }
    val b = async { slow(2) }
    println(a.await() + b.await())
}

What is next

A lessons course for this language is on the way, and the reference is already available.

A course is on the way. For now only the reference is available; lessons and tasks will follow.