scalaif-statementconditional-operator

Ternary conditional operator in Scala


I would like to simplify this:

var countA: Int = 0
var countB: Int = 0

if (validItem) {
  if (region.equalsIgnoreCase( "US" )) {
    if (itemList > 0) {
      countB = 1
    } else {
      countA = 1
    }
  } else {
    countB = 1
  }
} else {
  countA = 1
}

How do I use the ternary conditional operator in Scala?


Solution

  • This might be a bit confusing for a "newbie", but you could attach a ternary method to the Boolean class like so.

    implicit class Ternary[T](condition: Boolean) {
      def ??(a: => T, b: => T): T = if (condition) a else b
    }
    

    Usage:

    (4 == 4)??("yes","no")         // res0: String = yes
    ("abc".length < 2).??(1,0)     // res1: Int = 0
    List('c').isEmpty.??('X','+')  // res2: Char = +