-
Notifications
You must be signed in to change notification settings - Fork 0
/
When expression.kt
89 lines (69 loc) · 2.18 KB
/
When expression.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
fun main (args: Array<String>){
/*
Kotlin provides a special when expression to perform different actions depending on the value
of a variable. It can replace if and make code more readable.
The program below performs addition, subtraction, and multiplication of two integers.
It uses when to decide which operation to perform
*/
val(var1, op, var2) = readln().split("")
val a = var1.toInt()
val b = var1.toInt()
when(op){
"+" -> println(a + b)
"-" -> println(a - b)
"*" -> println(a * b)
else -> println("Unknown operator")
}
/**
* Case: if there are several cases to handle
* A comma can be used to combine various cases as seen below
*/
when(op){
"+", "plus" -> println(a + b)
"-", "minus" -> println(a -b)
"*", "times" -> println(a * b)
else -> println("Unknown operator")
}
/**
* Complex blocks with multiple statements as branches can be used
*/
when(op) {
"+", "plus" -> {
val sum = a + b
println(sum)
}
"-", "minus" -> {
val diff = a - b
println(diff)
}
"*", "times" -> {
val product = a * b
println(product)
}
else -> println("Unknown operator")
}
/**
* When as an expression
* Every branch returns something, and an else branch is required
* */
val result = when(op){
"+","plus" -> a + b
"-","minus" -> a - b
"*", "times" -> a * b
else -> "unknown operator"
}
println(result)
/**
* When without arguments
* In this case, every branch condition is a simple boolean expression
* A branch is executed when its condition is ture.
* If several conditions are true, only the first one will be executed
*/
val n = readln().toInt()
when{
n == 0 -> println("n is equal to 0")
n in 1..100 -> println("n is between 1 and 100")
n > 300 -> println("n is greater than 300")
//else branch is optional here
}
}