- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 82字
- 2021-06-24 14:13:30
The when without argument
The second form of when is used without an argument, and is a drop-in replacement for if...else clauses. This can sometimes result in clearer code, especially if many of the conditions are simple comparisons. The following example shows a way of writing the same code using when:
fun whenWithoutArgs(x: Int, y: Int) { when { x < y -> println("x is less than y") x > y -> println("X is greater than y") else -> println("X must equal y") } }