Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Kotlin for Java Developers Modelling Solitaire The Surface Is Fine and Powdery

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,795 Points

Use 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,795 Points

In Kotlin adding val or var in front of the constructor parameters upgrades the parameter to a property which are accessible outside the class.