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 trialTonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsUse of Companion Objects in Kotlin
Ben Deitch mentions that parameters of the constructor have a pretty limited scope; we can only use these parameters in initializing a property or inside the init block.
Inside the Card class constructor, he declares a parameter called value which I note is not inside the companion class
//value property declared inside the constructor
class Card(val value: Int, val suit: String, var faceUp: Boolean = false){
companion object{
val clubs = "Clubs";
val spades = "Spades"
val hearts = "Hearts"
val diamonds = "Diamonds"
}
}
In the FoundationFile Class on the addCard () function, the teacher is able to access the value property never mind it is supposed to have limited scope and is not static or a companion object.
class FoundationFile (val suit: String){
fun addCard(card: Card): Boolean{
var nextValue = 0;
if (cards.size>0){
// value card is used here yet it has a limited scope and not static (companion object)
nextValue =cards.last().value +1
}
//value property from the Card class is also used here
if (card.suit==suit && card.value== nextValue){
cards.add(card)
return true
}
return false
}
}
My question is how is the value property accessible on another class yet it is not static and has a limited scope? Please help
1 Answer
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsIn Kotlin adding val or var in front of the constructor parameters upgrades the parameter to a property which are accessible outside the class.