Search code examples
scalaenumscompareenumeration

Scala Enumeration Compare Order


object CardNum extends Enumeration
{
    type CardNum = Value;
    val THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
    TEN, JACK, QUEEN, KING, ACE, TWO = Value
}

Above shows my enumeration. I want to compare the ordering of the enumeration such as checking whether it is following the order defined in my enumeration. I tried with the compareTo() method but it will only return the value of -1, 0, or 1. Unlike Java which will return the distance between the enumeration. For example i used this code.

1 - println(CardNum.FIVE.compareTo(CardNum.EIGHT))
2 - println(CardNum.SEVEN.compareTo(CardNum.EIGHT))

Both sentence 1 and sentence 2 gave me the same result of -1, which makes me unable to detect if the user is following the order of the enumeration. In Java there will be no problem, as sentence 1 will give me the result -3 and sentence 2 -1. Is there method to do so in Scala? Sorry I am quite inexperience in Scala.


Solution

  • You can use the difference between element ids:

    scala> CardNum.FIVE.id - CardNum.EIGHT.id
    res1: Int = -3
    
    scala> CardNum.SEVEN.id - CardNum.EIGHT.id
    res2: Int = -1