Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

koltin
if-else
communitycreator

How to use the if...else statement and expression in Kotlin

Programming Bytes

By using the if statement, we can execute a block of code if the passed condition is valid; otherwise, the else block will be executed.

fun main(args: Array<String>) {

  var day: String = "sunday"

  if(day.equals("sunday")) {
    println("Holiday")
  } else {
    println("Working Day")
  }

}

In the above code, we have two blocks of code, one inside if and another inside else. We checked if the day is sunday in the if condition. If the condition is true, then the if block will be executed; otherwise, the else block will be executed.

If there is only one statement inside the if, then there is no need for curly braces.

if…else expression

if...else can be used as an expression that will return a value. When we are using if...else as an expression, the else block is mandatory.

Example

// Example 1
fun main(args: Array<String>) {
  var day: String = "sunday"
  var isWorkingDay =  if(day.equals("sunday")) {
      false
  } 
  else {
    true
  }
  println("Is working day => " + isWorkingDay);

}

In the above code, we have used the if...else expression. In that, either the last expression of the if block will be returned or the else block will be returned.

fun main(args: Array<String>) {
  var a = 1
  var b = 2
  var max = if(a > b) a else b
  println("max($a, $b) = $max")
}

We have skipped the curly brace for the if and else blocks in the above code.


We can also have multiple if..else and nested if...else statements

fun main(args: Array<String>) {
  var experienceInYears = 10
  var designation: Any = if(experienceInYears == 1) {
      "Trainee"
  } else if (experienceInYears in 1..2) {
      "Junior Deveoper"
  } else if (experienceInYears in 3..5) {
      "Senior Developer"
  } else if (experienceInYears in 6..10) {
      "Product Manager"
  } else if (experienceInYears in 11..20) {
      "Manager"
  } else {
      "Fire him/her"
  }
  println(designation)
}

In the above code, we have used multiple if...else statements as expressions.

RELATED TAGS

koltin
if-else
communitycreator
RELATED COURSES

View all Courses

Keep Exploring