Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference when adding a private modifier to arguments in a Kotlin's constructor?

Tags:

android

kotlin

I'm not sure about the difference between the following two constructors written in Kotlin

class ConcreteItem(val title: String) : Item() {

}

and

class ConcreteItem(private val title: String) : Item() {
}

As you can see, the only difference is the "private" modifier before the title field. How will it affect the scope of the title field?

like image 336
rookiedev Avatar asked Dec 24 '22 11:12

rookiedev


2 Answers

The following code:

class ConcreteItem(val title: String) : Item() {
}

is a shortcut for:

class ConcreteItem(title: String) : Item() {
    val title: String = title
}

where lack of explicit access modifier for val title implies public:

class ConcreteItem(title: String) : Item() {
    public val title: String = title
}

Similarly, the following code:

class ConcreteItem(private val title: String) : Item() {
}

is a shortcut for:

class ConcreteItem(title: String) : Item() {
    private val title: String = title
}

Taking that in account, the difference between two declarations is simply declaring public property vs private property.

like image 98
code_x386 Avatar answered Dec 28 '22 06:12

code_x386


if the private modifier is applied, then a public "getter" won't be synthesized whereby other classes can interrogate the value of "title". otherwise will be.

like image 33
homerman Avatar answered Dec 28 '22 06:12

homerman