KOTLIN: When Expression

From OnnoWiki
Jump to navigation Jump to search

Sumber: https://www.tutorialspoint.com/kotlin/kotlin_when_expression.htm

Consider a situation when you have large number of conditions to check. Though you can use if..else if expression to handle the situation, but Kotlin provides when expression to handle the situation in nicer way. Using when expression is far easy and more clean in comparison to writing many if...else if expressions. Kotlin when expression evaluates a section of code among many alternatives as explained in below example.

Kotlin when matches its argument against all branches sequentially until some branch condition is satisfied.

Kotlin when expression is similar to the switch statement in C, C++ and Java.


Pertimbangkan situasi ketika Anda memiliki sejumlah besar kondisi untuk diperiksa. Meskipun Anda dapat menggunakan ekspresi if..else if untuk menangani situasi, tetapi Kotlin menyediakan ekspresi when untuk menangani situasi dengan cara yang lebih baik. Menggunakan ekspresi ketika jauh lebih mudah dan lebih bersih dibandingkan dengan menulis banyak ekspresi if...else if. Kotlin ketika ekspresi mengevaluasi bagian kode di antara banyak alternatif seperti yang dijelaskan dalam contoh di bawah ini.

Kotlin ketika mencocokkan argumennya terhadap semua cabang secara berurutan hingga beberapa kondisi cabang terpenuhi.

Kotlin ketika ekspresi mirip dengan pernyataan switch di C, C++ dan Java.


Example

fun main(args: Array<String>) {
   val day = 2

   val result = when (day) {
     1 -> "Monday"
     2 -> "Tuesday"
     3 -> "Wednesday"
     4 -> "Thursday"
     5 -> "Friday"
     6 -> "Saturday"
     7 -> "Sunday"
     else -> "Invalid day."
   }
   println(result)
}

When you run the above Kotlin program, it will generate the following output: Ketika Anda menjalankan program Kotlin di atas, itu akan menghasilkan output berikut:


Tuesday

Kotlin when as Statement

Kotlin when can be used either as an expression or as a statement, simply like a switch statement in Java. If it is used as an expression, the value of the first matching branch becomes the value of the overall expression.

Kotlin ketika dapat digunakan baik sebagai ekspresi atau sebagai pernyataan, seperti pernyataan switch di Java. Jika digunakan sebagai ekspresi, nilai cabang pertama yang cocok menjadi nilai ekspresi keseluruhan.

Example

Let's write above example once again without using expression form:

Mari kita tulis contoh di atas sekali lagi tanpa menggunakan bentuk ekspresi:


fun main(args: Array<String>) {
   val day = 2 

   when (day) {
     1 -> println("Monday")
     2 -> println("Tuesday")
     3 -> println("Wednesday")
     4 -> println("Thursday")
     5 -> println("Friday")
     6 -> println("Saturday")
     7 -> println("Sunday")
     else -> println("Invalid day.")
   }
}

When you run the above Kotlin program, it will generate the following output:

Ketika Anda menjalankan program Kotlin di atas, itu akan menghasilkan output berikut:

Tuesday

Combine when Conditions

We can combine multiple when conditions into a single condition.

Kita dapat menggabungkan beberapa kondisi saat menjadi satu kondisi.


Example

fun main(args: Array<String>) {
   val day = 2

   when (day) {
     1, 2, 3, 4, 5 -> println("Weekday")
     else -> println("Weekend")
   }
}

When you run the above Kotlin program, it will generate the following output:

Ketika Anda menjalankan program Kotlin di atas, itu akan menghasilkan output berikut:


Weekday

Range in when Conditions

Kotlin ranges are created using double dots .. and we can use them while checking when condition with the help of in operator.

Rentang Kotlin dibuat menggunakan titik ganda .. dan kita dapat menggunakannya saat memeriksa kondisi saat dengan bantuan operator in.

Example

fun main(args: Array<String>) {
   val day = 2

   when (day) {
     in 1..5 -> println("Weekday")
     else -> println("Weekend")
   }
}

When you run the above Kotlin program, it will generate the following output:

Ketika Anda menjalankan program Kotlin di atas, itu akan menghasilkan output berikut:


Weekday

Expression in when Conditions

Kotlin when can use arbitrary expressions instead of a constant as branch condition.

Kotlin kapan dapat menggunakan ekspresi arbitrer alih-alih konstanta sebagai kondisi cabang.


Example

fun main(args: Array<String>) {
   val x = 20
   val y = 10
   val z = 10
   
   when (x) {
      (y+z) -> print("y + z = x = $x")
      else -> print("Condition is not satisfied")
   }
}

When you run the above Kotlin program, it will generate the following output:

Ketika Anda menjalankan program Kotlin di atas, itu akan menghasilkan output berikut:


y + z = x = 20

Kotlin when with block of code

Kotlin when braches can be put as block of code enclosed within curly braces.

Kotlin ketika tanda kurung dapat diletakkan sebagai blok kode yang diapit oleh kurung kurawal.

Example

fun main(args: Array<String>) {
   val day = 2 

   when (day) {
     1 -> {
        println("First day of the week")
        println("Monday")
     }
     2 -> {
        println("Second day of the week")
        println("Tuesday")
     }
     3 -> {
        println("Third day of the week")
        println("Wednesday")
     }
     4 -> println("Thursday")
     5 -> println("Friday")
     6 -> println("Saturday")
     7 -> println("Sunday")
     else -> println("Invalid day.")
   }
}

When you run the above Kotlin program, it will generate the following output:

Ketika Anda menjalankan program Kotlin di atas, itu akan menghasilkan output berikut:


Second day of the week
Tuesday

Quiz Time (Interview & Exams Preparation)

Q 1 - Which of the following is true about Kotlin when expression?

A - It is used to compare a single value against multiple conditions

B - Kotlin when expression can be used in place of if..else if expression

C - Kotlin when branches can be integer, string, array or ranges

D - All of the above

Q 2 - Kotlin when can be used as an expression as well as a statement?

A - True

B - False

Q 3 - Kotlin when is inspired by which of the following Java statement

A - switch statement

B - if statement

C - do...while statement

C - None of the above


Referensi