17

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?

DIF
  • 2,470
  • 6
  • 35
  • 49
Joshua Yan
  • 173
  • 1
  • 4

2 Answers2

36

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

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
Miha_x64
  • 5,973
  • 1
  • 41
  • 63
0

You can try like this

class Sample(var id: Int, private var name:String) {

    // Backing field
    var _name: String = ""
        get() = name
        private set

}

fun main(args: Array<String>) {
     println("Hello World")

     val sample = Sample(1, "hello")
    //    println(sample.name); It's not possible
    println(sample._name)
}
VinayagaSundar
  • 1,673
  • 17
  • 18