0
votes

The following sample code snippet:

val deck = for {
  suit <- Suit.values
  rank <- Rank.values
} yield {
  println(s"$rank $suit")
  PlayingCard(suit, rank)
}
print(deck)

provides the following output:

Ace Hearths
Two Hearths
Three Hearths
Four Hearths
Five Hearths
Six Hearths
Seven Hearths
Eight Hearths
Nine Hearths
Ten Hearths
Jack Hearths
Queen Hearths
King Hearths
Ace Diamonds
Two Diamonds
Three Diamonds
Four Diamonds
Five Diamonds
Six Diamonds
Seven Diamonds
Eight Diamonds
Nine Diamonds
Ten Diamonds
Jack Diamonds
Queen Diamonds
King Diamonds
Ace Spades
Two Spades
Three Spades
Four Spades
Five Spades
Six Spades
Seven Spades
Eight Spades
Nine Spades
Ten Spades
Jack Spades
Queen Spades
King Spades
Ace Clubs
Two Clubs
Three Clubs
Four Clubs
Five Clubs
Six Clubs
Seven Clubs
Eight Clubs
Nine Clubs
Ten Clubs
Jack Clubs
Queen Clubs
King Clubs

TreeSet(Ace of Clubs, Two of Clubs, Three of Clubs, Four of Clubs, Five of Clubs, Six of Clubs, Seven of Clubs, Eight of Clubs, Nine of Clubs, Ten of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs)

I have absolutely no idea why this code correctly iterates over all cards, but only seems to return the last suit (being clubs)

1

1 Answers

3
votes

Maybe it's because you're building a TreeSet, but you've implemented equality for PlayingCard wrong so it's discarding elements that you want to keep. This would happen if PlayingCard.equals only considers the rank of the card, ignoring the suit.

If PlayingCard.equals was implemented so that it ignores the suit then whenever you add an Ace of any suit to the Set it will remove the previous Ace. This seems like the problem you're seeing.

To fix this, either change the definition of PlayingCard.equals to consider the suit or force a different collection type that doesn't care about equality, e.g. Vector:

val deck = for {
  suit <- Suit.values.toVector
  rank <- Rank.values.toVector
} yield {
  println(s"$rank $suit")
  PlayingCard(suit, rank)
}
print(deck)