Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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) {
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) {
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


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Kotlin: Using when as if-else if ladder

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×