Kotlin has introduced a new feature called if as an expression, which makes a programmer's life much easier. Instead of assigning a value in each if statement, Kotlin returns the value from a successful code block, which can be stored in a variable. Before writing an if statement, add a variable name with an assignment operator as follows:
grade = if (studentMarks >= 90) {
"A"
}
See the following example with if as an expression, where grade will be assigned depending on studentMarks:
fun main(args: Array<String>) {
val studentMarks = 95
var grade = if (studentMarks >= 90) {
"A"
} else if (studentMarks >= 80) {
"B"
} else if (studentMarks >= 70) {
"C"
} else if (studentMarks >= 60) {
"D"
} else {
"F"
}
println ( "Student achieved " + grade )
}
Notice that it is not required to write grade = "A" or grade = "D" in each else…if block, but while using if as an expression, there is one thing to remember—if as an expression cannot be used without an else statement:
val grade = if (studentMarks >= 90) {
"A"
}
Kotlin will throw the following compile-time error:
'if' must have both main and 'else' branches if used as an expression