Kotlin

Kotlin if else expression

In this post, we’ll learn If else conditional statement in Kotlin. We’ll cover each small topic, that has related to IF-ELSE. will see If expression and if multiple conditions with the help of an example. So lets started

If else conditional Statement

Let’s see the below here we simply define two values. Now down the side, I want to get max value using if condition in Kotlin

fun main(args: Array<String>) {
    val a = 10
    val b = 15

    var result: Int
    if (a > b) {
        result = a
    } else {
        result = b
    }
    print("Greater value is $result")
}

Above expression, we simply wrote a code for get a max value. So let us run the code and see, here we find simply 15, So we had simply written code to find the maximum value of these two number .

Output is

 Greater value is 15
 Process finished with exit code 0

IF as Expression

The conditional statement is very similar to java. But in Kotlin we have If expression. What mean of that? We can use if condition as expression. How to do that let’s see  

fun main(args: Array<String>) {
    val a = 10
    val b = 15

    val result = if (a > b) {
        a
    } else {
        b
    }
    print("Greater value is $result")
}

As you see our code is more cleaner, So here what I’m doing is, this is the if as an expression. Now simply if a is greater than b then assign a to the result variable else assign b.

Means which is a maximum value that will be assigned to the result variable. In the end, simply print the result variables. Let us run the code the output will we same. So in Kotlin we can make if condition to the return some value, that called IF as Expression

Multiple if statements

Suppose I have multiple lines of code inside the if condition so which value will be return? and which will store in the result variable.

   fun main(args: Array<String>) {
    val a = 10
    val b = 15

    val result = if (a > b) {
        print("A is greater")
        a
    } else {
        print("B is greater")
        b
    }
    print("Greater value is $result")
}

Let see above code here I’m adding a block of code inside the if condition. In this condition where we have multiple lines of code with in the IF block also else block. So which of the following will be return 

 Now as per the rule, The last statement that is define inside the if condition will be returned.In this example last statement is a and b

Conclusion

So in this way we are actually using the if-else condition as an expression now this if the condition is returning some value. So that us why we calling IF expression

Read our new article switch statement in Kotlin

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments