Ginsan
Ginsan

Reputation: 341

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.

Upvotes: 0

Views: 2947

Answers (2)

gabrielgiussi
gabrielgiussi

Reputation: 9575

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.

Upvotes: 0

Kolmar
Kolmar

Reputation: 14224

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

Upvotes: 2

Related Questions