DEV Community

ivanleomk
ivanleomk

Posted on

Part 2 : Control Flow with Kotlin

Motivation

This article is written for more advanced developers which are looking to get a quick grasp on the Kotlin Language for work or for some interesting projects.

We cover installation, basic syntax and a quick introduction to functions in this article which is Part 2 in a long series.

Note : I do use a For-Loop in this article to simulate draws from a finite sequence from 0 to 10 but the syntax is relatively similar to other languages.

Control Flow in Kotlin

In Kotlin, we have two main constructs that we can use when it comes to making decisions.

If-Else

The first is the if-else construct which we can see an example below.

fun main(){
    val controlling:Int = 3;

    if(controlling < 4){
        println("The Value is less than 4")
    }
    else{
        println("The value is larger than 4")
    }
}
Enter fullscreen mode Exit fullscreen mode

This doesn't seem very useful, so let's perhaps do a quick example where we randomly generate 4 numbers instead using kotlin's random package.

import kotlin.random.Random

fun main(){
    var controlling:Int;
    for( i in 1..4){
        controlling = (0..10).random()
        if(controlling < 4){
            println("The Value of $controlling is less than 4")
        }
        else{
            println("The value of $controlling is larger than 4")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

which we can further simplify into

import kotlin.random.Random

fun main(){
    var controlling:Int;
    for( i in 1..4){
        controlling = (0..10).random()
        println(
            "The value of $controlling is ${
                if(controlling > 4) "greater" else "less"
            } than 4"
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

This in turn gives the same output of

The value of 7 is greater than 4
The value of 10 is greater than 4
The value of 5 is greater than 4
The value of 8 is greater than 4
Enter fullscreen mode Exit fullscreen mode

When to use When? :)

Another potential way of expressing this logic is by using a when construct.

import kotlin.random.Random


fun main(){
    var controlling:Int;
    for( i in 1..4){
        controlling = (0..10).random()
        when(controlling){
            in 0..4 -> println("$controlling is less than or equal to 4")
            in 5..10 -> println("$controlling is greater than 4")
            else -> println("Unsupported Number")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's walk through this logic a little bit

  1. We know that (0...10).random() will yield us a number within the range of 0 to 10. This is an inclusive range which means we can get 0 and 10. *Therefore, we know that we only need to match against numbers that lie within this range. *

  2. We want to print "less than 4" if we obtain a number less than or equal to 4 otherwise we print "greater than 4". This means that we are essentially breaking our number into two disjoint sets or groups.

These are the two groups

1,2,3,4 ( expressed as 1..4 )
5,6,7,8,9,10 ( expressed as 5..10)

  1. Therefore, we can simply rewrite using the when loop to check membership in either side.

In general, I find that When is more useful when you have more than two or three choices to make.

Some useful shorthand syntax to remember when using When can be seen below

  1. Finite number of distinct options

Let us first rewrite our original example above to take advantage of the , syntax. Notice that we now do not utilise the in keyword.

import kotlin.random.Random


fun main(){
    var controlling:Int;
    for( i in 1..4){
        println(i)
        controlling = (0..10).random()
        when(controlling){
            0,1,2,3,4 -> println("$controlling is less than or equal to 4")
            5,6,7,8,9,10 -> println("$controlling is greater than 4")
            else -> println("Unsupported Number")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Eg 2. Multiple Conditions

Let's write a short snippet that helps us check if a user can log in based on a given username or password.

Note : We could easily replace the following with an if-else loop if you prefer. Personally, I think this boils down to a matter of preference, When is just cleaner in general to me.


fun main(){
    val correct_username = "john.smith"
    val correct_password = "applebees"

    val username_attempts = listOf(
        "antique","john.smith","john.smith"
    )

    val password_attempts = listOf(
        "applebees","apples","applebees"
    )

    for(i in 0..2){

        when{
            correct_password == password_attempts[i] && correct_username == username_attempts[i] -> println("Login Succesful")
            correct_username != username_attempts[i] -> println("Wrong Username")
            correct_password != password_attempts[i] -> println("Wrong Password")
            else -> println("Horrible Attempt")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Kotlin provides two useful constructs which help us to be able to deal with user-input and implement logic in our code. In the next article, we'll look at how we can reduce redundant code by using Loops!

Top comments (0)