Thursday 14 December 2017

Kotlin: Using when as if-else if ladder

You can also use ‘when’ expression as if-elseif ladder. If you do not specify any argument to when expression, it can be used as if-else if ladder.

ConditionDemo.kt
fun main(args: Array<String>) {
 var marks: Int = 65

 if (marks < 35)
  println("You are failed");
 else if (marks < 50)
  println("You are passed and got third class");
 else if (marks < 60)
  println("You are passed and got second class");
 else if (marks < 70)
  println("You are passed and got first class");
 else
  println("You are passed and got distinction");
}


Output
You are passed and got first class

You can implement above if-else if-else logic using when expression like below.

WhenDemo.kt

fun main(args: Array<String>) {
 var marks: Int = 65

 when {
  (marks < 35) -> println("You are failed")
  (marks < 50) -> println("You are passed and got third class")
  (marks < 60) -> println("You are passed and got second class")
  (marks < 70) -> println("You are passed and got first class")
  else -> println("You are passed and got distinction")
 }

}

Output
You are passed and got first class



Previous                                                 Next                                                 Home

No comments:

Post a Comment