In this tutorial you will learn about Whenstatement via simple step by step examples.

Example 1: Simple When Example

Let us look at a simple When statement example written in Kotlin Programming Language. Follow the following steps:

Step 1: Create Project

  1. Open your favorite Kotlin IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Add Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Our code will comprise the following Kotlin files:

  • When.kt
  1. In your editor or IDE, create a file known as When.kt.
  2. Then add the following code:

(a). When.kt

package When

fun main(args : Array<String>) {
    var x = 101
    val greater = { x : Int -> x > 100 }

    //This is one hell of a flexible switch statement
    when {
        x in 1..50 -> print("In range")
        greater(x) -> print("Great")
        x == 50 -> print("Exact match")
        else -> print("Outside range")
    }
}

Step 4: Run

Copy the code, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

More Kotlin When Expressions Examples

Let us look at a simple When Expressions example written in Kotlin Programming Language. Follow the following steps:

Step 1: Create Project

  1. Open your favorite Kotlin IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Add Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Write code as follows in the examples shown:

  • AnalyzeInput.kt
  • BmiWhen.kt
  • GermanOrdinals.kt
  • MatchingAgainstVals.kt
  • MixColors.kt

Example 1: Analyze Input with when

Our code will comprise the following Kotlin files:

  1. In your editor or IDE, create a file known as AnalyzeInput.kt.
  2. Then add the following code:

(a). AnalyzeInput.kt

// WhenExpressions/AnalyzeInput.kt

package whenexpressions
import atomictest.*

class Coordinates {
  var x: Int = 0
    set(value) {
      trace("x gets $value")
      field = value
    }
  var y: Int = 0
    set(value) {
      trace("y gets $value")
      field = value
    }
  override fun toString() = "($x, $y)"
}

fun processInputs(inputs: List<String>) {
  val coordinates = Coordinates()
  for (input in inputs) {
    when (input) {                   // [1]
      "up", "u" -> coordinates.y--   // [2]
      "down", "d" -> coordinates.y++
      "left", "l" -> coordinates.x--
      "right", "r" -> {              // [3]
        trace("Moving right")
        coordinates.x++
      }
      "nowhere" -> {}                // [4]
      "exit" -> return               // [5]
      else -> trace("bad input: $input")
    }
  }
}

fun main() {
  processInputs(listOf("up", "d", "nowhere",
    "left",  "right", "exit", "r"))
  trace eq """
    y gets -1
    y gets 0
    x gets -1
    Moving right
    x gets 0
  """
}

Example 2: BMI Caluclator with when expression

  1. Next create another file known as BmiWhen.kt.
  2. And add the following code:

(b). BmiWhen.kt

// WhenExpressions/BmiWhen.kt

package whenexpressions
import atomictest.eq

fun bmiMetricOld(
  kg: Double,
  heightM: Double
): String {
  val bmi = kg / (heightM * heightM)
  return if (bmi < 18.5) "Underweight"
    else if (bmi < 25) "Normal weight"
    else "Overweight"
}

fun bmiMetricWithWhen(
  kg: Double,
  heightM: Double
): String {
  val bmi = kg / (heightM * heightM)
  return when {
    bmi < 18.5 -> "Underweight"
    bmi < 25 -> "Normal weight"
    else -> "Overweight"
  }
}

fun main() {
  bmiMetricOld(72.57, 1.727) eq
    bmiMetricWithWhen(72.57, 1.727)
}

Example 3: German Ordinals with when

  1. Next create another file known as GermanOrdinals.kt.
  2. And add the following code:

(c). GermanOrdinals.kt

// WhenExpressions/GermanOrdinals.kt

package whenexpressions
import atomictest.eq

val numbers = mapOf(
  1 to "eins", 2 to "zwei", 3 to "drei",
  4 to "vier", 5 to "fuenf", 6 to "sechs",
  7 to "sieben", 8 to "acht", 9 to "neun",
  10 to "zehn", 11 to "elf", 12 to "zwoelf",
  13 to "dreizehn", 14 to "vierzehn",
  15 to "fuenfzehn", 16 to "sechzehn",
  17 to "siebzehn", 18 to "achtzehn",
  19 to "neunzehn", 20 to "zwanzig"
)

fun ordinal(i: Int): String =
  when (i) {                            // [1]
    1 -> "erste"                        // [2]
    3 -> "dritte"
    7 -> "siebte"
    8 -> "achte"
    20 -> "zwanzigste"
    else -> numbers.getValue(i) + "te"  // [3]
  }

fun main() {
  ordinal(2) eq "zweite"
  ordinal(3) eq "dritte"
  ordinal(11) eq "elfte"
}

Example 4: Matching Against a list with when

  1. Next create another file known as MatchingAgainstVals.kt.
  2. And add the following code:

(d). MatchingAgainstVals.kt

// WhenExpressions/MatchingAgainstVals.kt

import atomictest.*

fun main() {
  val yes = "A"
  val no = "B"
  for (choice in listOf(yes, no, yes)) {
    when (choice) {
      yes -> trace("Hooray!")
      no -> trace("Too bad!")
    }
    // The same logic using 'if':
    if (choice == yes) trace("Hooray!")
    else if (choice == no) trace("Too bad!")
  }
  trace eq """
    Hooray!
    Hooray!
    Too bad!
    Too bad!
    Hooray!
    Hooray!
  """
}

Example 5: When with sets

  1. Next create another file known as MixColors.kt.
  2. And add the following code:

(e). MixColors.kt

// WhenExpressions/MixColors.kt

package whenexpressions
import atomictest.eq

fun mixColors(first: String, second: String) =
  when (setOf(first, second)) {
    setOf("red", "blue") -> "purple"
    setOf("red", "yellow") -> "orange"
    setOf("blue", "yellow") -> "green"
    else -> "unknown"
  }

fun main() {
  mixColors("red", "blue") eq "purple"
  mixColors("blue", "red") eq "purple"
  mixColors("blue", "purple") eq "unknown"
}

Step 4: Run

Copy the code, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code License](https://github.com/BruceEckel/AtomicKotlinExamples/blob/master/Copyright.txt)