Kotlin Conditions and Loops

Mercy Jemosop
4 min readNov 15, 2023

Boolean, While loops, If…Else, when, while loop

Introduction

Hello, this tutorial will cover Boolean, while loops, if…else statements, when and while loops.

Terms used in this blog

Operand is a term used to refer to a value or expression used to perform an operation.

Expression is a combination of values, variables, operators and function calls that evaluates to a single result. It is used to :

  • assign values to a variable
  • Passing arguments to functions
  • Performing calculations
// Expression
val day = "Tuesday"
val result = when (day) {
"Monday" -> println("Happy Monday!")
"Tuesday" -> println("It's Tuesday!")
else -> println("Have a great day!")
}
println(result)
//output
It's Tuesday!

Statement is a complete instruction that instructs the program to perform an action. It does not evaluate to a value and does not produce direct results. It is used to:

  • Control the program flow
  • Alter data
  • Perform operations
val day = "Monday"
when (day) {
"Monday" -> println("Happy Monday!")
"Tuesday" -> println("Have a great day!")
"Wednesday" -> println("Hump day!")
else -> println("Have a nice weekend!")
}
//output
Happy Monday!

Boolean

This is a data type which represents objects that have two values: true or false, yes or no, on or off . It’s nullable counterpart is represented using Boolean? which has a null value.

//nullable boolean
val isTrue: Boolean? = null
//output
null

Boolean built in operations:

  • | | which is disjunction (logical OR)

It returns true if any of the given condition is true

val isRaining: Boolean = true
val isCloudy: Boolean = false
print(isRaining || isCloudy)
//output
true
  • && which is conjunction (logical AND)

It returns true if both values are true otherwise false

print(isRaining && isCloudy)
//output
false
  • ! which is negation ( logical Not)

It reverses the value of a Boolean operand

print(!isRaining) //true
print(!isCloudy)//false
// output
false
true

Kotlin If…Else

This statements are used to execute both the true parts and false parts of a given condition.

If condition is true, the if block of code is executed and if condition is false the Else part is executed.

if(condition){
// block of code to be executed if the condition is true
}else {
// block of code to be executed if the condition is false
}


if(2> 3){
print("True")
}else{
print("false")
}
//output
false

Else if condition is used to specify a new condition. We use this when we need to perform multiple test or check multiple conditions.

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

example
if (2 > 3) {
print("Condition1 True")
} else if (3 > 2) {
print("Condition2 True ")
} else {
print("false")
}
//output
Condition2 True

Note: You can omit the curly braces {} when if has only one statement

if(2<3) print("Condition  True ") else print("Condition  false ")
//output
Condition True

Logical conditions supported by kotlin

Less than if(2 < 3)
Less than or equal to if(2 <= 3)
Greater than if(2 > 3)
Greater than or equal to if(2 >= 3)
Equal to if(2 == 3)
Not Equal to if( 2 != 3)

Kotlin when

Defines a conditional expression with multiple branches. It is used instead of if…else because it is easy to read. It selects on of many block of code to be executed. It is similar to switch statement in java.

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used as an expression or a statement.

Each branch starts with a value followed by an arrow (->) and a result.

1 -> "Condition is true"

If it used as an expression, the value of the first matching branch becomes the value of the overall expression.

// Expression
val result = when (dayOfWeek) {
"Monday" -> println("Happy Monday!")
"Tuesday" -> println("It's Tuesday!")
else -> println("Have a great day!")
}
println(message) // Output: 2

The else branch is evaluated if none of the other branch conditions are satisfied.

Note: if when is used as an expression the else branch is mandatory unless the compiler can prove that all possible cases are covered with branch conditions :

enum class entries and sealed class subtypes

enum class Bit {
ZERO, ONE
}

val numericValue = when (getRandomBit()) {
Bit.ZERO -> 0
Bit.ONE -> 1
// 'else' is not required because all cases are covered
}

sealed class is a class that is marked with a sealed keyword. It is used to define a closed set of subclasses. They are used to restrict users from inheriting that class. It is similar to enum classes.

sealed interface Error

sealed class IOError(): Error

class FileReadError(val file: File): IOError()
class DatabaseError(val source: DataSource): IOError()

object RuntimeError : Error

fun log(e: Error) = when(e) {
is FileReadError -> { println("Error while reading file ${e.file}") }
is DatabaseError -> { println("Error while reading from database ${e.source}") }
is RuntimeError -> { println("Runtime error") }
// the `else` clause is not required because all the cases are covered
}

statement

enum class Color {
RED, GREEN, BLUE
}

when (getColor()) {
Color.RED -> println("red")
Color.GREEN -> println("green")
Color.BLUE -> println("blue")
// 'else' is not required because all cases are covered
}

when (getColor()) {
Color.RED -> println("red") // no branches for GREEN and BLUE
else -> println("not red") // 'else' is required
}

Kotlin While Loop

While and do-while loops execute their body continuously while their condition is satisfied.

while loop checks the condition and if it’s satisfied, executes the body and then returns to the condition check.

var x=4 
while (x > 0) {
x--
print(x)
}
//output
3210

do-while loop executes the body and then checks the condition. if it’s satisfied, the loop repeats.

    do {
x--
print(x)
} while (x > 0)
//output
3210

Resources:

Kotlin documentation

W3school

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy