Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSourabh Pal
210 PointscardsInPile in forEachIndexed function
How the line val cardsInPile: MutableList<Card> = Array(i+1, {deck.drawCard()}).toMutableList()
draws cards from deck more than once? I think the for each loop iterates over each tableauPile index i.e. 7 times. But when it creates the cardsInPile for each iteration how come each array item withdraws a card from the deck?
2 Answers
andren
28,558 PointsThe lambda you pass as a second argument to the Array
constructor is used to generate the default value of the items in the array.
That means that if you have this code for example:
CardsInPile: MutableList<Card> = Array(5, {deck.drawCard()}).toMutableList()
Kotlin would call deck.drawCard() once to set the value of the first element, then again to set the value of the second element, then again to set the value of the third element, and so on. Until all of the elements had a default value.
So the above code would call deck.drawCard()
5 times, since there are 5 elements in the array.
Maybe this example from the official kotlin docs clarifies how it works a bit better:
// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5, { i -> (i * i).toString() })
Sourabh Pal
210 PointsThank you for you answer. Now i totally understand how it works. It just skipped out of my mind that its a lambda expression