Kotlin

Kotlin was created by JetBrains, announced in 2011 and released as 1.0 in 2016. It is designed to be a more concise and safer Java that interoperates with it completely. Google made it the preferred language for Android in 2019.

Paradigm: Object-Functional and Beyond

What Makes Kotlin Special

  • Null safety in the type system. String can never be null, and String? can. The compiler forces you to handle the second case with ?., ?: or a check.
  • Data classes. data class User(val name: String) generates equality, printing, copy and destructuring.
  • Sealed types and when. A sealed interface plus an exhaustive when expression gives algebraic data types and pattern-style dispatch.
  • Extension functions. You can add a method to any existing class, such as fun String.shout(), without inheritance.
  • Functional style built in. Lambdas, higher-order functions and rich collection operations (map, filter, mapNotNull, sumOf) are everyday tools. val is preferred over var.
  • Coroutines. Lightweight suspending functions (the kotlinx.coroutines library) write asynchronous code sequentially, much like async/await.

Example: Null safety, sealed types and extensions

data class User(val name: String, val age: Int?)

sealed interface Shape
data class Circle(val r: Double) : Shape
data class Rect(val w: Double, val h: Double) : Shape

fun area(s: Shape): Double = when (s) {
    is Circle -> Math.PI * s.r * s.r
    is Rect -> s.w * s.h
}

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

fun main() {
    val users = listOf(User("Ada", 36), User("Linus", null), User("Grace", 45))

    println(users.mapNotNull { it.age }.average())   // 40.5
    println(users[1].age ?: "unknown")               // unknown
    println(users.first().copy(age = 37))            // User(name=Ada, age=37)
    println("kotlin".shout())                        // KOTLIN!

    val shapes: List<Shape> = listOf(Circle(1.0), Rect(2.0, 3.0))
    println(shapes.sumOf { area(it) })               // 9.141592653589793
}

How It Works

  • age: Int? says the age may be missing. mapNotNull drops the missing ones, and ?: (the Elvis operator) supplies a default.
  • copy(age = 37) builds a new User with one field changed, so the data class stays immutable.
  • when on a sealed interface must be exhaustive, and inside each branch the compiler already knows the smart-cast type (s.r, s.w).
  • fun String.shout() adds a method to String. It is resolved statically, so it costs nothing at run time.

History and Where It Is Used

Kotlin is used for Android apps, back-end services (Spring, Ktor), scripts (Gradle build files) and, with Kotlin Multiplatform, code shared between Android, iOS, web and desktop. It compiles to JVM bytecode, JavaScript and native code. See also the full Kotlin roadmap on this site.

Learn More