HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Instead of writing many if..else expressions, you can use the when expression, which is much easier to read
Instead of writing many if..else
expressions, you can use the when
expression, which is much easier to read.
It is used to select one of many code blocks to be executed:
Use the weekday number to calculate the weekday name:
val day = 4
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day."
}
println(result)
// Outputs "Thursday" (day 4)
The when
expression is similar to the switch
statement in Java.
This is how it works:
when
variable (day) is evaluated onceelse
is used to specify some code to run if there is no matchday
is 4
, meaning "Thursday" will be printed