Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In kotlin, how to make the setter of properties in primary constructor private?

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?

like image 451
Joshua Yan Avatar asked Jun 07 '17 06:06

Joshua Yan


People also ask

What is private VAR in Kotlin?

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.

How do you set setters and getters in Kotlin?

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.

What is private constructor Kotlin?

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 ...

How do you use the Kotlin getter setter?

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.


1 Answers

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

like image 134
Miha_x64 Avatar answered Sep 27 '22 21:09

Miha_x64