Why Kotlin
Open an Android app made in the last few years, look at its source, and it will very likely be Kotlin. Look inside the back end of a bank or an online marketplace, and you may find Kotlin there too, running on the same Java Virtual Machine as the Java code next to it. Open a Gradle build file in almost any modern Java project, and the build.gradle.kts you see is Kotlin as well.
Kotlin is a statically typed language made by JetBrains, the company behind the IntelliJ IDEA development environment. It was designed by people who wrote a great deal of Java and wanted a language that kept everything good about the Java platform (its virtual machine, its libraries, its tools) while removing the friction they met every day. The result is a language with a few clear priorities:
- Conciseness without cleverness. A data class with equality, hashing and a readable
toStringis one line. Types are usually inferred. But Kotlin avoids terse symbols and magic; code reads like what it does. - Safety, especially from null. In Kotlin a
Stringcan never benull; a value that might be missing has a different type,String?, and the compiler makes you handle the missing case. The most common crash in Java programs, theNullPointerException, becomes rare. - Interoperability. Kotlin calls Java and Java calls Kotlin, in the same project, with no wrappers. Any Java library is a Kotlin library.
- Pragmatism. Features earn their place by solving real problems in real codebases, and the tooling (the compiler, IntelliJ IDEA, Android Studio, Gradle) is first-class.
Today Kotlin is used in three main places: Android, where Google has recommended it as the preferred language since 2019; server-side development, with frameworks such as Spring and Ktor; and Kotlin Multiplatform, which shares code (business logic, networking, sometimes user interfaces) between Android, iOS, desktop and the web.
A short history
JetBrains began working on Kotlin around 2010 in its Saint Petersburg office, with Andrey Breslav as lead designer, and announced it publicly in July 2011. The name comes from Kotlin Island, near Saint Petersburg, an echo of Java being named after an island too. The language was developed in the open, and version 1.0 shipped in February 2016 with a promise of backward compatibility.
The turning point came in 2017, when Google announced official support for Kotlin on Android; in 2019 Google declared Android development "Kotlin-first". The Kotlin Foundation was created by JetBrains and Google to steward the language. Coroutines, Kotlin's approach to asynchronous programming, became stable in 2018. Kotlin Multiplatform was declared stable in late 2023.
Kotlin 2.0, released in 2024, replaced the compiler's front end with a new one, called K2, that is faster and the foundation for future language features. The 2.x releases since then have added features such as guard conditions in when, non-local break and continue, and multi-dollar string interpolation. JetBrains ships a language release about every six months with smaller tooling releases in between. This course uses Kotlin 2.4, and every program in it was compiled with the Kotlin 2.4.21 compiler and run on JDK 21.
One language, several targets
Kotlin is a language, not a runtime. Its compiler has several back ends:
- Kotlin/JVM produces Java bytecode, exactly the kind of
.classfilesjavacproduces. The JVM cannot tell Kotlin code from Java code. This is the target used in this course, on Android, and on servers. - Kotlin/Native produces machine code (via LLVM) for iOS, macOS, Linux and Windows, with no JVM at all.
- Kotlin/JS and Kotlin/Wasm produce JavaScript and WebAssembly for browsers.
Kotlin Multiplatform builds on these: you write shared code once, in a "common" module that may use only the Kotlin standard library and multiplatform libraries, and platform-specific code where you need it.
On the JVM, Kotlin adds one small thing to your program: the Kotlin standard library, a JAR with functions such as println, listOf and maxBy. Everything else comes from the JVM and from Java's own library, which Kotlin uses directly. That is why a Kotlin program can call java.time.LocalDate without any adapter, and why a team can add Kotlin to an existing Java codebase one file at a time.
Installing and running Kotlin
There are several good ways to get started:
- No installation. The Kotlin Playground runs Kotlin in your browser. It is ideal for the short programs in the first lessons.
- IntelliJ IDEA or Android Studio. Both include Kotlin support. Create a new Kotlin project and the IDE sets up Gradle and a JDK for you. This is how most professionals work.
- The command-line compiler. Download
kotlincfrom the Kotlin releases on GitHub, or install it with a package manager such as SDKMAN! (sdk install kotlin) or Homebrew. You also need a JDK (version 17 or newer is a good choice; this course used JDK 21), because the compiler runs on the JVM and so do its programs.
With the command-line tools, a program goes from source to running in two steps:
kotlinc main.kt -include-runtime -d main.jar # compile, bundling the Kotlin standard library
java -jar main.jar # run it on the JVM-include-runtime puts the standard library inside the JAR so that plain java -jar can run it. Checking the version is kotlinc -version; on the machine this course was tested on, it printed info: kotlinc-jvm 2.4.21 (JRE 21.0.13.1+2-LTS). In real projects you will rarely call kotlinc yourself: Gradle (or Maven) does it, as you will see in Java interoperability, Gradle and testing.
A first program
fun main() {
println("Hello, Kotlin!")
val firstYear = 2011
val stable = 2016
println("Announced in $firstYear, version 1.0 in $stable: ${stable - firstYear} years later.")
println("This program runs on Kotlin ${KotlinVersion.CURRENT}.")
}Hello, Kotlin!
Announced in 2011, version 1.0 in 2016: 5 years later.
This program runs on Kotlin 2.4.21.Compared with Java, notice what is not there:
- No class.
fun main()is a top-level function: Kotlin does not require code to live inside a class. (The compiler still puts it in a class, named after the file:main.ktbecomes the classMainKt, because the JVM needs one.) - No semicolons. A line break ends a statement. Semicolons are allowed but almost never written.
- No types on the variables.
val firstYear = 2011declares a read-only variable whose type,Int, the compiler infers from the value. It is still statically typed: try to assign a string to it later and the program will not compile. - String templates. Inside a string,
$firstYearinserts a variable's value, and${stable - firstYear}inserts the value of any expression.
println is a function from the Kotlin standard library. KotlinVersion.CURRENT describes the version of the standard library the program is running with.
A program with a function and a loop
fun greeting(city: String, hour: Int): String {
val part = if (hour < 12) "morning" else if (hour < 18) "afternoon" else "evening"
return "Good $part, $city!"
}
fun main() {
val cities = listOf("Lagos", "Lima", "Hanoi", "Kuala Lumpur")
val hours = listOf(8, 13, 19, 23)
for ((city, hour) in cities.zip(hours)) {
println(greeting(city, hour))
}
println("${cities.size} greetings; the longest city name is ${cities.maxBy { it.length }}.")
}Good morning, Lagos!
Good afternoon, Lima!
Good evening, Hanoi!
Good evening, Kuala Lumpur!
4 greetings; the longest city name is Kuala Lumpur.Reading it line by line:
fun greeting(city: String, hour: Int): Stringdeclares a function. Parameters are written name: Type, and the return type comes after the parentheses. Kotlin puts the name first and the type second everywhere, which reads naturally ("city, a string") and makes the type easy to leave out where it can be inferred.ifis an expression: it produces a value, soval part = if (...) "morning" else ...needs no separate conditional operator. Kotlin has noc ? a : bconditional operator; it does not need one.listOf(...)creates a read-only list.cities.zip(hours)pairs the two lists element by element, andfor ((city, hour) in ...)takes each pair apart into two variables (destructuring).cities.maxBy { it.length }passes a lambda (the code in braces) tomaxBy. A lambda with one parameter can refer to it asit. You will write lambdas constantly in Kotlin; Control flow, when and functions explains them properly.
Java's library, from Kotlin
Because Kotlin/JVM compiles to the same bytecode as Java, the whole Java standard library is available, with some conveniences:
import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
// Java's standard library, used directly from Kotlin
val today = LocalDate.of(2026, 11, 19)
val newYear = LocalDate.of(2027, 1, 1)
println("$today is a ${today.dayOfWeek}") // getDayOfWeek() becomes a property
println("${ChronoUnit.DAYS.between(today, newYear)} days until $newYear")
val names = java.util.ArrayList<String>() // a Java collection class
names.add("Ada")
names.add("Grace")
println(names.joinToString(" & ")) // a Kotlin function on a Java object
}2026-11-19 is a THURSDAY
43 days until 2027-01-01
Ada & GraceJava's getDayOfWeek() method appears in Kotlin as the property dayOfWeek: Kotlin treats Java getters and setters as properties. There is no new keyword; you create an object by calling its constructor like a function. And Kotlin's own functions, such as joinToString, work on Java's collection classes, because Kotlin's collections are Java's collections underneath, viewed through Kotlin interfaces.
A compiler error
val means the variable cannot be reassigned. This program tries anyway:
fun main() {
val count = 1
count = 2
println(count)
}and kotlinc refuses it:
E.kt:3:5: error: 'val' cannot be reassigned.
count = 2
^^^^^The message gives the file, the line and column (3:5), a description, and the offending code underlined. Use var for a variable that genuinely needs to change, but prefer val: code where most names never change is far easier to follow, and Kotlin style guides recommend val by default.
Kotlin and Java at a glance
If you already know some Java, this table maps the most common constructs. If you do not, skip it; every row is taught properly in the lessons that follow.
| Idea | Java | Kotlin |
|---|---|---|
| Read-only variable | final String name = "Ada"; | val name = "Ada" |
| Mutable variable | int count = 0; | var count = 0 |
| Function | static int twice(int x) { return 2 * x; } | fun twice(x: Int) = 2 * x |
| String building | "Hi " + name + "!" | "Hi $name!" |
| Conditional value | x > 0 ? "pos" : "neg" | if (x > 0) "pos" else "neg" |
| Possibly missing value | any reference may be null | only String? may be null |
| Data holder | a record or a class with equals, hashCode, toString | data class Point(val x: Int, val y: Int) |
| Creating an object | new StringBuilder() | StringBuilder() |
| Inheritance | classes open unless final | classes final unless open |
Two habits will serve you from the first day. Let the compiler infer types for local variables, but write them on public functions, where they document the contract. And read the warnings IntelliJ IDEA or the compiler gives you: Kotlin's tools are good at suggesting the idiomatic form of what you wrote, and following those suggestions is one of the fastest ways to learn the language's style.
Common misconceptions
Misconception
"Kotlin is only for Android." Android made Kotlin famous, but it is widely used on servers (Spring has first-class Kotlin support, and Ktor is a Kotlin-native framework), in build scripts, and in multiplatform apps that share code with iOS.
Misconception
"Kotlin replaces Java, so I do not need to know anything about Java." On the JVM, Kotlin runs on Java's virtual machine and uses Java's libraries. Stack traces, profilers, the garbage collector and most libraries you meet are Java's. Kotlin developers who understand the platform underneath debug much faster.
Misconception
"Kotlin is slower than Java because it adds a layer." There is no interpreting layer: Kotlin compiles to ordinary bytecode, and the JVM's JIT compiles it like any other. Some Kotlin features (lambdas passed to inline functions, for example) can even produce leaner bytecode than the equivalent Java.
Misconception
"val makes an object immutable." It makes the variable read-only. val names = java.util.ArrayList<String>() cannot be pointed at another list, but the list itself can still change, as the interop example shows.
Where to go from here
- The Kotlin documentation has a tour of the basics and a reference for every feature. Its Kotlin Koans are short exercises that run in the browser.
- The Kotlin language specification is the precise definition, for when you need an exact answer.
- The Kotlin Playground is the quickest way to try the examples in the next lessons.
Next, Values, types and null safety looks at Kotlin's types, and at the feature that most changes how Kotlin code feels: the compiler's tracking of which values can be null.
Exercises
1. Why Kotlin, and a first program
Warm-upComputationalWhat does this program print?
fun main() {
val name = "Kotlin"
println("$name has ${name.length} letters")
}
2. Why Kotlin, and a first program
CoreComputationalWhat does this program print?
fun main() {
val price = 4
println("Total: $price * 3 = ${price * 3}")
}
3. Why Kotlin, and a first program
Warm-upComputationalWhat does this program print?
fun main() {
var total = 0
for (n in 1..5) {
total += n
}
println(total)
}
4. Why Kotlin, and a first program
Warm-upHumanWhich of these can the Kotlin compiler produce? Choose all that apply.
5. Why Kotlin, and a first program
CoreHumanWhat happens when you compile this?
fun main() {
val count = 1
count = 2
println(count)
}
6. Why Kotlin, and a first program
StretchHumanThe JVM can only run code that belongs to a class, but fun main() in the file main.kt is not inside any class. What is the name of the class the Kotlin compiler generates to hold it?
Further reading and resources
- Kotlin documentation · JetBrainsThe official guide, from basic syntax to coroutines and multiplatform.
- Kotlin Playground · JetBrainsWrite and run Kotlin in the browser with nothing installed.
- Kotlin command-line compiler · JetBrainsInstalling kotlinc and compiling to a runnable JAR.
- Kotlin releases · JetBrainsThe release cycle and the list of versions.
- Kotlin on Android · GoogleGoogle's own material on Kotlin as the preferred language for Android.
- Kotlin FoundationThe foundation, created by JetBrains and Google, that protects the language and its trademark.