if

4 0 0
                                        

syntax:

if(condition){

     //statement 1

}else {

     //statement 2

}

If condition is true, perform statement 1 but if false, perform statement 2. Take note that ternary operator (condition ? value1 : value2) is not use in here since ternary operator works just like if. Also if "if" is used in an expression, the last statement is the considered as the return value even if you did not used the keyword return.

syntax:

val name1 = if(condition){

     //statement 1

     // last statement 1

}else {

     // statement 2

     // last statement 2

}

We created a variable whose value depends on an if statement. If the condition is true, the last statement 1 is the value else if false, the last statement 2 is the value.


====================

fun main(){

     val x = 6

     val y = 9

     val answer = if(x > y){

          x - y

     }else {

          y - x

     }

     println("answer: $answer")

}

===================

Result:

answer: 3

Kotlin ProgrammingWhere stories live. Discover now