0
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.

Ginsan
  • 291
  • 1
  • 5
  • 13

2 Answers2

2

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
Kolmar
  • 14,086
  • 1
  • 22
  • 25
  • Thanks for your answer. I have been thinking of putting them into a List and use the indexOf method to compare them. But it looks like the id works. Thanks a lot. – Ginsan Oct 18 '16 at 10:14
0

You should include the logic described by Kolmar to know the distance between two cards inside the Enumeration or using an implicit class, this way its simpler to search references in the code and also make changes in a transparent way (e.g. this will allow you to change the enumeration order)

Inside the enumeration

object CardNum extends Enumeration {

  protected case class CardVal() extends super.Val {
    def distance(that: CardVal) = this.id - that.id
  }
  type CardNum = Val;
  val THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
  TEN, JACK, QUEEN, KING, ACE, TWO = CardVal()
}

Using a implicit class

implicit class EnhancedCard(card: CardNum.CardNum) {
  def distance(that: CardNum.CardNum): Int = card.id - that.id
}

With this solution you need to have the implicit class in scope.

gabrielgiussi
  • 9,245
  • 7
  • 41
  • 71