Friday, 15 December 2017

Kotlin: Use When as expression

You can use 'when' as expression. If you use 'when' as expression, the value of the matched branch will be the value of 'when' expression.

WhenDemo.kt
fun main(args: Array<String>) {
 var a : Int = 2
 var s : String = "cube"
 
 var result = when {
  s.equals("double") -> a * a
  s.equals("cube") -> a * a * a
  else -> a
 }
 
 println("result is $result")

}

Output

result is 8


Previous                                                 Next                                                 Home

No comments:

Post a Comment