if-else statement in Kotlin

You already know that if is a statement which executes a set of statements based on condition. But in Kotlin, if can be used as statement and expression.

Syntax of if-else as a statement

if(condition){
   //code to be executed when condition is true
}else{
   //code to be executed when condition is false
}

Example

public fun main(args: Array<String>) {
   var a: Int = 30;
   var b: Int = 20;
   if(a>b){
	   print("a is greater than b");
   }else{
	   print("b is greater than a");
   }
}

Output

a is greater than b

if-else as an Expression

An expression is a statement that evaluates to a value. In Kotlin, if...else control statement is expression. It means you can do three things with this features-

1. You can assign the value to a variable.

public fun main(args: Array<String>) {
   var a=12
   var b=14
   var max = if(a > b) a else b
   print(max)
}

2. You can return from a function.

fun max(): Int{
   return if(14 > 12) 14 else 12
}
public fun main(args: Array<String>) {
   var i: Int = max()
   print(i)
}

3. You can pass it as an argument to a function.

fun max(a: Int){
   print(a)
}
public fun main(args: Array<String>) {
   var i: Int = 10
   max(if(i>10) 12 else 14)
}

Note- When you use if...else statement as an expression, make sure you include else clause. If you forget to write else clause then you will get a compilation error.
Also, remember on thing, you can also use try...catch statement as an expression.