Kotlin Control Flow Statements It is used to control the flow of program structure, following types of expression in kotlin.
- if Expression
- if-else expression
- if-else if-else ladder expression
- nested if expression
if Expression : if the condition of if block is true than if block executes.
Syntax:
if(condation){
// if condition is true this block will be executed
}
fun main(args: Array<String>){
var a = 62
var b = 17
if(a>b){
// if condition is true this block will be executed
println("a is gretor than b")
}
}
Output
a is gretor than b
if-else Expression : if condition of If block is true than if block will be executed otherwise else block will be executed.
fun main(args: Array<String>) {
val a = 62
val b = 17
val result = if (a > b) {
"$a is greater than $b"
} else {
"$b is greater than $b"
}
println(result)
}
output
62 is greater than 17
if-else if-else Ladder Expression : if expression is true so only if block executes if returns false then if else if condition checks if true only else if block executes or returns false else block executes. let’s take an example.
fun main() {
val a = 62
if(a == 12){
println("a is 12")
}else if(a == 25){
println("a is 25")
}else{
println("a is not there")
}
}
Nested if Expression
Syntax:
if( condition1) {
// it Executes when condition1 is true
if(boolean_expression 2) {
// it Executes when condition2 is true
}
}
fun main() {
val a = 62
if(a < 100){
if(a == 62)
println("a is 62")
}else{
println("a is not there")
}
}
Output
a is 62