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 trialSai Krishna Katkam
Courses Plus Student 1,946 PointsHow can we use "val" keyword with MutableList in Kotlin?! Isn't it supposed to stop us from changing a value?
In the Solitaire app, Ben declares a property using val. I wonder how can a mutable object be declared as val?
class FoundationPile(val suit: String) {
val cards: MutableList<Card> = mutableListOf()
fun reset()
{
cards.clear()
}
}
1 Answer
Ben Deitch
Treehouse TeacherThat's actually not a mutable object. You can modify the contents of the list (even clearing it), but you're not actually changing the list itself; it's the same list just with different contents.
So while you can use the 'clear' method to reset the cards list, you couldn't set it equal to a new list.
val cards = mutableListOf()
cards.clear() // Ok
cards = mutableListOf() // Not ok