Kotlin When Expressions

What is When?

The when expression is used to check multiple conditions.

It replaces switch statements from other languages.

Basic Syntax

Loading...
Output:

Multiple Conditions

Loading...
Output:

Using Ranges

Loading...
Output:

When as an Expression

Loading...
Output:

Without Argument

Loading...
Output:

Full Example

Loading...
Output:

Why When is Important

  • Cleaner than if-else
  • More readable
  • Supports multiple conditions
  • Core Kotlin feature

Common Mistakes

  • Forgetting else branch
  • Incorrect range usage
  • Not using when as an expression

Practice

Categorize a number using when.

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic