Thuta Learning
Kotlin
BasicProgrammingBeginner

What is Kotlin?

KotlinLesson 220 min

What you'll walk away with

  • Separate the language (Kotlin) from the platforms it runs on (JVM, Android, JS, Native)
  • Show the four design goals (concise, safe, interoperable, tool-friendly) with code
  • Explain the difference between `String` and `String?` and predict whether a line compiles
  • Summarize where Java and Kotlin are the same and where they differ

Explain it simply

What is Kotlin, simply?

Compare Java and Kotlin to a building. The JVM is the solid building that people have used for many years. Java is the old front door and Kotlin is a newer, safer one. Both doors lead to the same rooms and furniture, which are the libraries.

From the point of view of someone writing it, Kotlin's two main strengths are short code and catching crashes caused by missing values at compile time. You will meet both in this lesson through examples.

Problem → Why → Solution

The problem: boilerplate and crashes that only appear at run time

Even a tiny Java class that only stores a title and a page count needs fields, a constructor and getters, and usually `equals()`, `hashCode()` and `toString()` as well. What you actually wanted to say, 'a Book has a title and pages', is buried under the plumbing.

The second problem is worse. The last line below compiles in Java, but `subtitle` is `null`, so the program crashes with a `NullPointerException` only when it runs. It is the kind of bug that surfaces in front of a user.

Book.java
public class Book {
    private final String title;
    private final int pages;

    public Book(String title, int pages) {
        this.title = title;
        this.pages = pages;
    }

    public String getTitle() { return title; }
    public int getPages() { return pages; }
    // ... plus equals(), hashCode() and toString()
}

// somewhere else:
String subtitle = null;
int length = subtitle.length();   // compiles, then NullPointerException

How Kotlin attacks both costs

For boilerplate, Kotlin has the `data class`: declare the fields and the compiler generates the getters, `equals()`, `hashCode()` and `toString()`. For nulls, the type system itself separates `String` (never null) from `String?` (may be null), so using a possibly missing value without checking it is a compile-time error.

Core concept: a modern language on a proven platform

Start by separating the language from the platform. Kotlin is the syntax, the compiler (`kotlinc`) and the standard library. The JVM is the platform that runs bytecode. Kotlin does not replace the JVM; it opens a new front door to it. That is why Java and Kotlin produce the same kind of bytecode and can share every library.

Kotlin was designed around four goals. The table below shows what each one looks like in code.

GoalWhat you see in code
Concise`data class Book(val title: String, val pages: Int)` replaces the whole Java class above in one line
Safe`String` can never hold null, and with `String?` the compiler makes you handle the missing case
InteroperableKotlin calls Java libraries directly, and Java can call Kotlin code
Tool-friendlyMade by an IDE company, so completion, refactoring and Java-to-Kotlin conversion work well

Here is how the compiler guards against a missing value. Write `val subtitle: String = null` and you get the compile error `null cannot be a value of a non-null type 'String'`. Declare `String?` and then call `subtitle.length` directly, and you get `only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'`. The crash Java shows at run time, Kotlin shows while you are still typing.

Know the targets as well. Kotlin/JVM produces bytecode and is used for servers, desktop programs and tools, and Android apps can be written in Kotlin too. Kotlin/JS produces JavaScript, and Kotlin/Native produces native binaries that need no JVM. Kotlin Multiplatform compiles one shared module separately for each of those targets. Every example in this course runs on Kotlin/JVM.

Mental model: a new door into a proven building
  1. You write Kotlin
  2. It compiles to Java-style bytecode
  3. Existing Java libraries just work
  4. Java can call your Kotlin back

Learning Kotlin means learning a new language, but not starting over with a whole new ecosystem.

General pattern: top-level declarations

kotlin
data class TypeName(val field: FieldType)

fun helperName(param: ParamType): ResultType {
    return expression
}

fun main() {
    println(helperName(value))
}

At the top level of a Kotlin file you can write classes and functions directly, with no wrapper class around everything. The program starts at the `main` function.

A first taste of Kotlin

This program gathers the ideas of the lesson in one place: a data class, a list, a lambda with filter, a for loop, a nullable type and a safe call. Do not expect to understand every symbol yet, because each one gets its own lesson later. What to notice is how short and readable the code is.

Library.kt
data class Book(val title: String, val pages: Int)

fun main() {
    val shelf = listOf(
        Book("Kotlin in a Day", 120),
        Book("Null Safety", 80),
        Book("Coroutines", 210)
    )

    val long = shelf.filter { it.pages > 100 }
    for (book in long) {
        println("${book.title} has ${book.pages} pages")
    }

    val subtitle: String? = null
    println("Subtitle length: ${subtitle?.length ?: 0}")
}

Code breakdown

  1. A data classdata class Book(val title: String, val pages: Int)

    This single line asks the compiler for everything the Java class needed: fields, constructor, getters, `equals()`, `hashCode()` and `toString()`. Writing `Book("Null Safety", 80)` is enough to create an object.

  2. A list of objectsval shelf = listOf(

    `listOf(...)` creates a read-only list. Kotlin works out that the type of `shelf` is `List<Book>`, so you do not have to write it.

  3. A lambda in filterval long = shelf.filter { it.pages > 100 }

    The `it.pages > 100` in braces is a lambda: a tiny piece of work applied to each item. `it` is the current Book, and only the books where the test is true are kept.

  4. A for loopfor (book in long) {

    `for (book in long)` hands over one book at a time under the name `book` and runs the body once for each. Here it prints the two books with 120 and 210 pages.

  5. A nullable typeval subtitle: String? = null

    The `?` in `String?` declares that this variable may hold `null`. `String` and `String?` are two different types, and the compiler checks them separately.

  6. Safe call and defaultprintln("Subtitle length: ${subtitle?.length ?: 0}")

    `subtitle?.length` reads the length only when subtitle is not null, and yields null instead of crashing otherwise. `?: 0` substitutes 0 when the result is null, so the output is `0`.

You should see
Kotlin in a Day has 120 pages
Coroutines has 210 pages
Subtitle length: 0

The same ideas in Java and Kotlin

This table helps whether you already know Java or not. Kotlin is widely used alongside Java, so when a library's documentation shows Java code, you can translate it into Kotlin as you read.

IdeaJavaKotlin
A name that never changesfinal String name = "Aye";val name = "Aye"
Print a lineSystem.out.println(name);println(name)
Text containing a value"Hi " + name + "!""Hi $name!"
Create an objectnew Book("Kotlin", 120)Book("Kotlin", 120)

The families are alike: `if`, `for` and `class` mean the same thing in both. The differences are that Kotlin needs no `new`, no semicolons and no class around `main`. The runtime is the same: both languages share the garbage collector and the JDK standard library.

In real projects

How teams mix Java and Kotlin in practice

Because Java and Kotlin share bytecode, teams do not rewrite a large Java project from scratch. They add new `.kt` files next to the existing `.java` files, and both kinds compile together in one project. IntelliJ IDEA can even convert a Java file into a Kotlin file. The converted result is a starting point, though, and usually needs tidying into proper Kotlin style.

Most library documentation is written in Java, so every Kotlin developer needs to be able to read it. With that skill you can use Spring, the Android SDK and other JVM libraries from Kotlin without hesitation. In code review, there is less boilerplate to read, and because `String` and `String?` are separate types, a reviewer can see from the type alone whether null is handled. These benefits show most in large codebases.

Common mistakes

Common mistakes

1. Writing Java in Kotlin clothing

Writing getter and setter methods by hand, typing `new`, or keeping the semicolons does not break Kotlin, but it throws away what makes Kotlin worth using. Use properties, data classes and default values to keep the code simple.

2. Believing null safety removes every NullPointerException

Inside Kotlin code the compiler keeps watch. But values returned by a Java library may or may not be null and Kotlin cannot always tell (these are called platform types), and writing `!!` tells the compiler to stop checking. A crash can come back in exactly those places.

3. Assuming Kotlin needs its own special runtime

A Kotlin/JVM program runs on an ordinary JVM. All it needs is a JDK (or JRE) and the Kotlin standard library. Bundling that library into the jar (`-include-runtime`) is covered in the Get Started lesson.

Mini challenge

Mini challenge: your own playlist

Create a Song data class, keep only the songs longer than 3 minutes and print them, then safely print a guest artist that may be null.

  • Declare a `Song` data class with a `title` (String) and `seconds` (Int)
  • Create three songs with `listOf` and keep only those longer than 180 seconds with `filter`
  • Print each remaining song with its title and minutes (seconds / 60)
  • Give a `String?` guest the value null and print `solo` when it is null
Playlist.kt
// TODO: declare a data class Song with a title (String) and seconds (Int)

fun main() {
    // TODO: build a listOf three Song values
    // TODO: keep only the songs longer than 180 seconds (filter)
    // TODO: print each remaining song: title and whole minutes
    // TODO: a nullable String? guest set to null; print it, or "solo" when null
}

Expected: Monsoon (4 min) Echo (3 min) Guest: solo

Show hint

Filter with `filter { it.seconds > 180 }`. For the possibly-null value use the Elvis operator `?:` as in `guest ?: "solo"`. Dividing one Int by another drops the fraction, so 245 / 60 is 4.

Show solution
Playlist.kt
data class Song(val title: String, val seconds: Int)

fun main() {
    val playlist = listOf(Song("Dawn", 150), Song("Monsoon", 245), Song("Echo", 200))

    val longSongs = playlist.filter { it.seconds > 180 }
    for (song in longSongs) {
        println("${song.title} (${song.seconds / 60} min)")
    }

    val guest: String? = null
    println("Guest: ${guest ?: "solo"}")
}

Quick quiz 1 / 3

Which statement correctly describes how Kotlin relates to the JVM?

Quick quiz 2 / 3

Which declaration does the Kotlin compiler reject?

Quick quiz 3 / 3

With `val subtitle: String? = null`, what does `println(subtitle?.length ?: 0)` print?

What to remember

  • Kotlin is the language and the JVM is the platform that runs its bytecode; keep the two apart.
  • The four design goals are concise, safe, interoperable and tool-friendly.
  • `String` can never be null and `String?` can, and the compiler checks the two separately.
  • Kotlin uses Java libraries directly, but values coming back from Java can still bring null crashes.

Kotlin releases — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What is Kotlin? | Thuta Learning