Learn: Kotlin Conditionals, Ranges, and “When”
Learn: Kotlin Conditionals, Ranges, and “When”
Overview:
In this tutorial, we are looking into conditionals, ranges, and the “when” statement in the Kotlin language. This tutorial also covers conditional operators, logical operators, and a variety of syntax that are used with each topic. If you’re already familiar with other programming languages, such as Java, C, C++, C#, etc… you will find that the first part of this tutorial on conditionals and their operators will be a review.
Requirements:
- Understand how to define variables in Kotlin
- (Recommended) If you’re following along, you should do so with the IntelliJ IDEA IDE – it’s FREE.
Source Code:
https://github.com/codetober/kotlin-conditionals-ranges-when
Watch the video instead:
IF Statement and IF/ELSE Statements
When you want to measure something against another, you make a comparison or a check. We make this comparison by evaluating a conditional statement; which generally consists of two or more pieces of data that are separated by logical operators and/or comparison operators. Kotlin supports the same primary operators that many other programming languages, like Java. We will have a closer look at these operators after a few brief code
snippets.
var examScore = 95 if(examScore == 100){ println("Amazing! Perfect Grade!") }
The example above shows our two pieces of data: examScore
and 100
; as well as the comparison operator that is being used to evaluate the data: ==
. What this condition is saying, in plain speech is, “Is examScore equal to 100? If so, print some output text”. Anything between the {
curly braces of the IF statement will execute as long as the condition evaluated to true – this means that if we wanted to print multiple lines of text or make another comparison, we could do that! In this example, examScore
does not pass the condition and therefore the println( ... )
statement will not execute.
Assuming that we want to handle the case where our examScore is not equal to 100, we could use another IF statement.
var examScore = 95 if(examScore == 100){ println("Amazing! Perfect Grade!") } if(examScore != 100){ var perfectScore = false println("Better luck next time...") }
However, this is not the recommended approach as it is unclear that the two conditions are actually related. Another developer looking at this code might wonder “Why are we checking both conditions?”. Instead, we use an ELSE or ELSE/IF statement to handle the scenario where the previous comparison was unsuccessful.
var examScore = 95 if(examScore == 100){ println("Amazing! Perfect Grade!") } else { var perfectScore = false println("Better luck next time...") } // OR we could do this: if(examScore == 100){ println("Amazing! Perfect Grade!") } else if(examScore < 90){ println("You managed an 'A-' grade") } else if(examScore < 80){ println("You managed a 'B' grade") } else { println("Better luck next time.") }
Comparison Operators
In addition to the comparators already used in this tutorial, Kotlin supports the following comparison operators:
== | True when: The value on the left and right are equal |
!= | True when: The value on the left and right are not equal |
< | True when: The value on the left is less than the value on the right |
<= | True when: The value on the left is less than OR equal to the value on the right |
> | True when: The value on the left is greater than the value on the right |
>= | True when: The value on the left is greater than OR equal to the value on the right |
=== | True when: The instance on the left has the same reference as the value on the right |
!== | True when: The instance on the left does NOT have the same reference as the value on the right |
Logical Operators
These operators can be used to combine multiple comparisons in a single conditional statement.
! | ‘NOT’: False -> True or True -> False |
|| | ‘OR’: If the condition on either side of this operator is true, it passes the check |
&& | ‘AND’: If BOTH of the conditions on the sides of this operator are true, it passes the check. Fails if one is not true |
// This will execute some logic if, the examScore is 100 OR if the exam was skipped if(examScore == 100 || skippedExam){ // Do something here }
“When” Statement
Kotlin supports another type of logical control statement which you may not be familiar with, the when
statement. It’s is a good practice to consider using a when statement instead of an if/else statement once there is a need for several else/if conditions; reading the when statement is generally easier. The when statement uses an abbreviated syntax to represent the action taken ->
val examScore = 95 val outputText = when(examScore) { 100 -> "Perfect. A+" else -> "Not so good." } println(outputText)
In the example above, we are setting the value of the outputText
variable based on the examScore
variable. This statement evaulates to, “When examScore equals 100, return the value ‘perfect. A+’, otherwise, return the value ‘Not so good.’. We will explore another more detailed example in the next section of this tutorial.
Ranges
Ranges all us specify values from the left side to the right side, using the syntax: ..
like this: 1..6
. This notation is inclusive, so, the previous example would represent all of the numbers from 1-6 (inclusively): 1, 2, 3, 4, 5, 6. However, if we use this notation for descending order, it is not inclusive of the lower boundary. 6..1
includes the values: 6, 5, 4, 3, 2 (not 1). Another way to write this statement would be to use the term until
. Until is a excludes the lower boundary of the operation, similar to how < and > are not inclusive. If you want to descend AND be inclusive, you must use the keyword downTo
.
1..6
= 1,2,3,4,5,6
6..1
= 6,5,4,3,2
6 until 1
= 6,5,4,3,2
6 downTo 1
= 6,5,4,3,2,1
Kotlin also allows this notation for other common ranges, such as characters. a..z
will include all of the characters from a-z and a..Z
will include a-z+A-Z.
To check if a value contained by this range you use the in
keyword. 4 in 1..6
(true)
The next example shows how we can use ranges with both if/else and when statements. As well as demonstrate how we can use an if statement to assign a value to a variable.
val examScore = 95 val outputText = when(examScore) { 100 -> "Perfect! A+" in 90..99 -> "Pretty good! A" in 80..99 -> "Nice. B" else -> "Try again" } println(outputText) // Alternatively, we could write the same logic using if + else/if statements val outputText = if(examScore == 100){ "Perfect! A+" } else if(examScore in 90..99){ "Pretty good! A" } else if(examScore in 80..89){ "Nice. B" } else { "Try again" }
That’s it! Congratulations on making it all the way through this tutorial and continuing your quest to craft amazing code! If you liked this tutorial, please share it 🙂 Comment below with any questions or issues you faced.