In kotlin, how to make the setter of properties in primary constructor private?
class City(val id: String, var name: String, var description: String = "") {
fun update(name: String, description: String? = "") {
this.name = name
this.description = description ?: this.description
}
}
I want the setter of properties name
to be private, and the getter of it public, how can I do?
In Kotlin, private modifiers allow only the code declared inside the same scope, access. It does not allow access to the modifier variable or function outside the scope.
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'. The data type of 'name' is String and we shall initialize it with some default value.
The kotlin private constructor is one of the constructor types, and it is used to stop the object creation for the unwanted case; if the user has decided to create the object for themselves accordingly, the memory will be allocated for the specific instance and also the class methods which is used for referring the ...
When you instantiate object of the Person class and initialize the name property, it is passed to the setters parameter value and sets field to value . Now, when you access name property of the object, you will get field because of the code get() = field . This is how getters and setters work by default.
The solution is to create a property outside of constructor and set setter's visibility.
class Sample(var id: Int, name: String) {
var name: String = name
private set
}
Update:
They're discussing it here: https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With