Scala for yield loop 不提供预期的输出

Scala for yield loop not providing expected output

以下示例代码片段:

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

提供以下输出:

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)

我完全不知道为什么这段代码可以正确地遍历所有牌,但似乎 return 最后一套(作为梅花)

可能是因为您正在构建 TreeSet,但是您为 PlayingCard 实现了错误的相等性,因此它丢弃了您想要保留的元素。如果 PlayingCard.equals 只考虑牌的点数而忽略花色,就会发生这种情况。

如果实施 PlayingCard.equals 以便它忽略花色,那么每当您将任何花色的 A 添加到 Set 时,它都会删除之前的 A。这似乎是您遇到的问题。

要解决此问题,请更改 PlayingCard.equals 的定义以考虑花色或强制使用不关心相等性的不同集合类型,例如Vector:

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