Reputation: 113
Disclaimer: I am fairly new to any contemporary kind of coding. (BASIC an Pascal back in high school, a bit of Python a few years ago, and now I'm trying to teach myself Scala.)
This code is supposed to generate a randomized deck of cards with suits and values I customize in the first couple of lines. I have code that works, using mutable variables, but I always read it's better to try to avoid mutable variables, so I tried using "yield" instead. This was the result after I modified the code:
import util.Random.shuffle
val suits = Vector[String]("s", "m", "p")
val values = Vector[Int](1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 5, 5, 9)
class Card(val suit:String, val value:Int) {}
class Deck() {
var cardsInDeck:Vector[Card] = Vector()
}
def makeDeck(suits:Vector[String], values:Vector[Int]):Vector[Card] = {
for (i <- suits) yield {
for (j <- values) new Card(i, j)
}
}
val TheDeck = new Deck
TheDeck.cardsInDeck = util.Random.shuffle(makeDeck(suits, values))
for (i <- TheDeck.cardsInDeck) {
println(s"${i.suit}${i.value}")
}
This gives me an error message, pointing at the arrow after 'i' and saying type mismatch.
Is there anything sort of like this that will work?
If not, do you think I should just stick with the original mutable variable version? (I'm assuming you can imagine how that basically went--start with a default-valued variable, and add to it one element at a time while iterating through the nested loops.)
Finally, I'm guessing Scala's already got some method or other built in that lets me do this for free. I think it's valuable to work out how to do it manually for general pedagogical purposes, but if there's a one-liner method out there I really should be using I'm interested in learning about it.
Thank you in advance...
Upvotes: 0
Views: 977
Reputation: 13667
def makeDeck(suits: Vector[String], values: Vector[Int]): Vector[Card] = {
for {
i <- suits
j <- values
} yield new Card(i, j)
}
You forgot the second yield in front of new Card
. However, there is no need to nest the for loops, instead structure them like above.
You should consider making cardsInDeck
into a val
and a constructor parameter, so Deck
can be immutable like Card
is. It would also be convenient for Deck
and Card
to be case classes.
Upvotes: 1