【问题标题】:In kotlin, how to make the setter of properties in primary constructor private?在 kotlin 中,如何将主构造函数中的属性设置器设为私有?
【发布时间】:2017-06-07 06:21:23
【问题描述】:

在kotlin中,如何将主构造函数中的属性设置器设为私有?

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

我希望 name 属性的 setter 是私有的,而它的 getter 是公开的,我该怎么做?

【问题讨论】:

标签: constructor kotlin


【解决方案1】:

解决方案是在构造函数之外创建一个属性并设置setter的可见性。

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

    var name: String = name
        private set

}

更新:
他们在这里讨论:https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640

【讨论】:

    【解决方案2】:

    你可以这样试试

    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)
    }
    

    【讨论】:

    • 我认为会改变命名。 _name 在构造函数中,name 在属性中。
    • 你最终会有两个名字。在_nameset之后,get的返回值不会改变。
    • 添加二级构造函数可能是更好的解决方案
    • 正如@Miha_x64 指出的那样,您必须实现“支持字段”的设置器,以便它更改构造函数字段。
    猜你喜欢
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多