- 3.2) Given a double amount, write an expression to return "greater" if it is more than zero, "same" if it equals zero, and "less" if it is less than zero. Can you write this with if..else blocks? How about with match expressions?
- Answer
- First, here’s the if..else block (specifically an if..else-if..else block).
- scala> val amount = 2.143
- amount: Double = 2.143
- scala> if (amount > 0) "greater" else if (amount < 0) "lesser" else "same"
- res0: String = greater
- Second, the match expression that achieves the same purpose.
- scala> amount match {
- | case x if x > 0 => "greater"
- | case x if x < 0 => "lesser"
- | case x => "same"
- | }
- res1: String = greater
- Which solution do you prefer? I find the match expression a bit more readable but the if..else block is certainly more compact.