-
Notifications
You must be signed in to change notification settings - Fork 0
Kotlin If, When and While
Maria Maged M edited this page Apr 12, 2020
·
4 revisions
- if is nearly ubiquitous in computer programming.
if(i > 10) {
// Do something.
}
else {
// Do something else.
}if(i > 10) {
// Do something.
}
else {
// Do something else.
}
// Yes, it is the same as Java syntax.if(i > 10)
# Do something.
else
# Do something.
end val i = 3
if(i > 10) {
println("Something")
}
else {
println("Something else")
}-
For single-line conditional work, you can skip the braces.
val i = 3
if(i > 10) println("Something") else println("Something else")- It also supports
else ifin addition to a simple else:
val i = 3
if(i > 10) println("Something")
else if(i > 2) println("Something else")
else println("And now for something completely different")when is distinctive.
when is powerful.
when is used a lot in Kotlin programming.
- The closest analogy to
whenin Java is theswitchstatement. - Here, depending on the value of
foo, we evaluate one set of statement that follows the matchingcase(or thedefaultstatements, if there are no matches).
switch(foo) {
case 1:
// Do something.
break;
case 2:
// Do something else.
break;
default:
// Like, whatever.
}- Javascript also has a switch, with same syntax as Java.
-
Ruby uses
case, and it is the closest of the three in terms of matching the power ofwhen.
case foo
when 1
# Do something.
when 2
# Do something else.
else
# Like, whatever.
endThe most commonly-seen of when looks like a Java/ JavaScript switch or Ruby case, when you supply a value for comparison and set up different branch conditions to test against that value:
val i = 3
when(i) {
1 -> println("Something")
2 -> println("Something else")
else -> println("And now for something completely different")
}- Each branch has a
value. - That is compared to an
input.
- The
first matchhas its statement or blockevaluated, and everything else isskipped.- If there are no matches, the
elsestatement or block is evaluated.
- If there are no matches, the
- The -> separates the branch comparison to the stuff that should be executed if that branch comparison is met.
In this case, the output is:
And now for something completely different.
- Anything that can be compared using equality (==) can be used.
val things = "foo"
when (thingy) {
"foo" -> println("Something")
"bar" -> println("Something else")
else -> println("And now for something completely different")
}- However, you cannot mix types, unless *== happens to work to compare them.
- This, for example, fails with a compiler error, pointing out that
IntandStringareincompatible types:
val things = "foo"
when(things) {
"foo" -> println("Something.")
2 -> println("Something else.")
else -> println("And now for something completely different")
}