[[ If-else Statements ]] ⇣
Kotlin uses the same if/else statement structure as most of the C-like languages and uses the same comparison operators.
val name = "Link"
if(name == "Link"){
println("It's dangerous to go alone, take this!")
} else if (name == "Mario") {
println("The Princess is in Another Castle.")
} else {
println("Do a barrel roll!")
}💡 Kotlin has the
===and!==comparison operators, similar to Javascript. These operators evaluate based on reference
Conditional expression
A very nice feature of Kotlin language is to assign an if/else to a value.
val level = if(name == "Link") {
5
} else {
0
}
// You can omit the {}s when a branch contains one expression
val level = if(name == "Link") 5 else 0[[ Logical operators ]] ⇣
| AND | OR | NOT |
|---|---|---|
| && | || | ! |
[[ Range operator ]] ⇣
The
range operator
(..) can be used to create a range. A range includes all the values from the value on the left of the operator to the value of the right. E.g. 1..5 includes 1,2,3,4 and 5. Ranges can also be a sequence of characters.
if (level in 1..4) { // equivalent of i >= 1 && i <= 4
print(i)
}[[ When expressions ]] ⇣
The when expression is a switch-case in other languages like JavaScript but more powerful than the latter.
When a when statement is used as an expression, the compiler will require that the when statement is exhaustive, covering all possible input.
val race = "Hylian"
val popularCharacter = when (race) {
// this is using the `==` operator for comparison
"Hylian", "Human" -> "Link"
"Sheikah" -> "Impa"
"Zora" -> "Ruto"
else -> {
// This `else` branch adds a fallback option to satisfy
// the compiler regarding the exhaustive behavior of `when`
"Tingle"
}
}When expressions with variable declarations
Sometimes, we will use a when expression with an argument that we compute only for the sake of using it inside the when expression.
val playerLevel = experience/100 + 1
val playerTitle = when (playerLevel) {
1 -> "Noob"
in 2..10 -> "Level $playerLevel Chad"
else -> "Doge Knight"
}The previous code can be refactored like this, making the playerLevel variable scoped only inside the when statement.
val playerTitle = when (val playerLevel = experience/100 + 1) {
// ...
}When expressions without arguments
A when statement without an argument is an interchangeable if/else statement
val status = when {
experience > requiredExperience -> "Get more experience!"
experience == requiredExperience -> "You can level up!"
requiredExperience - experience < 25 -> {
"You're almost there, keep getting experience"
}
}[[ While loops ]] ⇣
while and do-while loops execute their body continuously while their condition is satisfied.
while (x > 0){
x--
}
do{
val data = getData()
} while (data != null) // `data` is visible here!