Private getter and public setter for a Kotlin property

后端 未结 3 1352
梦谈多话
梦谈多话 2020-12-05 09:17

How to make a property in Kotlin that has a private getter (or just do not have it) but has a public setter?

var status
private get

doesn\'

3条回答
  •  广开言路
    2020-12-05 09:39

    In current Kotlin version (1.0.3) the only option is to have separate setter method like so:

    class Test {
        private var name: String = "name"
    
        fun setName(name: String) {
            this.name = name
        }
    }
    

    If you wish to restrict external libraries from accessing the getter you can use internal visibility modifier allowing you to still use property syntax within the library:

    class Test {
        internal var name: String = "name"
        fun setName(name: String) { this.name = name }
    }
    
    fun usage(){
        val t = Test()
        t.name = "New"
    }
    

提交回复
热议问题