0Pricing
Kotlin Academy · Lesson

when as Expression

Return values from when.

when as Expression is a free Kotlin Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

when as an Expression

Kotlin's when is more than a switch statement. It is an expression, meaning it produces a value you can assign or return.

This makes branching logic concise and readable.

Returning a Value

When used as an expression, each branch supplies a result. The matching branch's value becomes the whole when result.

fun main() {
    val day = 3
    val name = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        else -> "Other"
    }
    println(name)
}

else Is Required

When used as an expression, when must be exhaustive. For arbitrary values that means an else branch.

Without it, the compiler cannot guarantee a value is produced.

fun grade(score: Int): String = when {
    score >= 90 -> "A"
    score >= 80 -> "B"
    else -> "C"
}

fun main() {
    println(grade(85))
}

Multiple Values per Branch

Separate several values with commas to share one branch.

This is cleaner than repeating the same body.

fun main() {
    val day = 6
    val type = when (day) {
        1, 2, 3, 4, 5 -> "Weekday"
        6, 7 -> "Weekend"
        else -> "Invalid"
    }
    println(type)
}

when Without an Argument

Omit the subject and each branch becomes a boolean condition.

This replaces a chain of if/else if with a tidy block.

fun main() {
    val temp = 18
    val feel = when {
        temp < 0 -> "Freezing"
        temp < 15 -> "Cold"
        temp < 25 -> "Mild"
        else -> "Hot"
    }
    println(feel)
}

Ranges in Branches

Branches can test ranges with in.

This expresses numeric buckets very naturally.

fun main() {
    val score = 73
    val band = when (score) {
        in 0..59 -> "Fail"
        in 60..79 -> "Pass"
        in 80..100 -> "Excellent"
        else -> "Invalid"
    }
    println(band)
}

Type Checks in Branches

Branches can check types with is.

The result of each branch can differ, and when returns the common type.

fun describe(x: Any): String = when (x) {
    is Int -> "Integer"
    is String -> "Text"
    else -> "Unknown"
}

fun main() {
    println(describe(42))
    println(describe("hi"))
}

Branch Blocks

A branch can be a block with multiple statements. The last expression in the block is its value.

fun main() {
    val n = 5
    val result = when {
        n > 0 -> {
            val doubled = n * 2
            "Positive, doubled is " + doubled
        }
        else -> "Non-positive"
    }
    println(result)
}

Returning when Directly

A function can return a when expression directly with a single-expression body.

This is a very common, clean Kotlin style.

fun sign(n: Int): String = when {
    n > 0 -> "positive"
    n < 0 -> "negative"
    else -> "zero"
}

fun main() {
    println(sign(-4))
}

Capturing the Subject

You can declare the subject inside when so it is available in the branches.

This keeps a temporary value scoped tightly.

fun describeLength(text: String): String = when (val len = text.length) {
    0 -> "empty"
    in 1..5 -> "short (" + len + ")"
    else -> "long (" + len + ")"
}

fun main() {
    println(describeLength("hello"))
}

Putting It Together

As an expression, when is a powerful value-producer:

  • Each branch supplies a result
  • else makes it exhaustive
  • Supports commas, ranges, types, and blocks
fun ticketPrice(age: Int): Int = when {
    age < 6 -> 0
    age < 18 -> 10
    age >= 65 -> 8
    else -> 15
}

fun main() {
    println(ticketPrice(4))
    println(ticketPrice(70))
}

Quick Check

Test your understanding of when as an expression.

Recap

You learned to use when as an expression:

  • It returns the matching branch's value
  • Needs else to stay exhaustive
  • Supports commas, ranges, type checks, and blocks

Next you will see how smart casts let the compiler narrow types for you.

Frequently asked questions

Is the “when as Expression” lesson free?

Yes — the full text of “when as Expression” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “when as Expression”?

Return values from when. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “when as Expression” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. when as Expression
  2. Smart Casts
  3. is and as Operators
  4. Exhaustive when
← Back to Kotlin Academy