Considering a move to Kotlin? Coming from a Java background? In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin. While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.

Case 5: Java has switch. Kotlin has when.

They look similar.

They are not.

The problem

We want to map values to readable output. Strings, numbers, ranges, types.

The Java way

private String getColorName(String color) {
  return switch (color) {
    case "R" -> "Red";
    case "G" -> "Green";
    case "B" -> "Blue";
    default -> "Orange";
 };
}

Usage:

getColorName("G"); // Returns "Green"

Clean. Modern. Still limited.

The Kotlin way

private fun getColorName(color: Any = "B"): String {
  return when (color) {
    "R" -> "Red"
    "G" -> "Green"
    "B" -> "Blue"
    in listOf("Y", "O") -> "Yellow or Orange"
    is Int -> "Number"
    else -> "Unknown"
  }
}

Usage:

getColorName("G") // Returns "Green"
getColorName(5)   // Returns "Number"
getColorName("Y") // Returns "Yellow or Orange"
getColorName("O") // Returns "Yellow or Orange"

when is an expression. Not just a control structure.

Why this matters

when:

  • supports multiple types

  • supports ranges

  • returns values naturally

Less ceremony. More power.

Takeaway

Java asks: “What value is this?” Kotlin asks: “What is this?”

Sources / Links

shadow-left