Tuesday, 12 December 2017

Why there is no ternary operator in kotlin?

Kotlin implements if statement as an expression, so it returns a value. Since if expression can return a value, we can achieve the ternary (?) functionality using if expression.

TernaryDemo.kt
fun main(args: Array<String>) {
 
 var a : Int = 10
 var b : Int = 20
 
 val max = if (a > b) a else b
 
 println("Maximum element is : $max")
}

Output
Maximum element is : 20


Previous                                                 Next                                                 Home

No comments:

Post a Comment