Newbie Newbie - 23 days ago 10
Scala Question

Ternary Operators 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 ternary operator in scala.

Answer

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 = +