Add conditional behavior in Kotlin

Last Updated on December 20, 2020 by AbdurRahman G Official | Md Ghufran Salafi

Add conditional behavior in Kotlin:


Solution code

fun main() {
    val myFirstDice = Dice(6)
    val rollResult = myFirstDice.roll()
    val luckyNumber = 4

    when (rollResult) {
        luckyNumber -> println("You won!")
        1 -> println("So sorry! You rolled a 1. Try again!")
        2 -> println("Sadly, you rolled a 2. Try again!")
        3 -> println("Unfortunately, you rolled a 3. Try again!")
        4 -> println("No luck! You rolled a 4. Try again!")
        5 -> println("Don't cry! You rolled a 5. Try again!")
        6 -> println("Apologies! you rolled a 6. Try again!")

class Dice(val numSides: Int) {
    fun roll(): Int {
        return (1..numSides).random()


  • Use an if statement to set a condition for executing some instructions. For example, if the user rolls the lucky number, print a winning message.
  • The Boolean data type has values of true and false and can be used for decision making.
  • Compare values using operators such as greater than (>), less than (<), and equal to (==).
  • Use a chain of else if statements to set multiple conditions. For example, print a different message for each possible dice roll.
  • Use an else statement at the end of a chain of conditions to catch any cases that may not be covered explicitly. If you cover the cases for 6-sided dice, an else statement would catch the 7 and 8 numbers rolled with an 8-sided dice.
  • Use a when statement as a compact form of executing code based on comparing a value.

Learn more

Practice on your own

Do the following:

  1. Change myFirstDice to have 8 sides and run your code. What happens?

Hint: When you increase the number of sides, your when statement does not cover all the cases anymore, so for uncovered cases, nothing is printed.

  1. Fix the when statement to account for all 8 sides. You can do this by adding cases for the additional numbers. Challenge: Instead of adding a new case for each number, use an else statement to catch all cases that are not covered explicitly.

Hint: You can add more cases to cover more sides. That is a good way to do this, if you want a different message for each number that can be rolled. Or, you can use an else statement and print the same message for all sides greater than the 6 covered by the current code.

  1. Change myFirstDice to have only 4 sides. What happens?

Hint: Changing the number of sides of the dice to less than what is covered by the when statement has no noticeable effect, since all the cases that can occur are covered.






Leave a Reply

Your email address will not be published. Required fields are marked *