Private getter and public setter for a Kotlin prop

2019-01-23 11:51发布

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't work with an error: Getter visibility must be the same as property visibility

In my case, the reason is for Java interop: I want my Java code to be able to call setStatus but not getStatus.

2条回答
Anthone
2楼-- · 2019-01-23 12:12

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"
}
查看更多
聊天终结者
3楼-- · 2019-01-23 12:17

It's impossible at the moment in Kotlin to have a property with a setter that is more visible than the property. There's a language design issue in the issue tracker on this, feel free to watch/vote for it or share your use cases: https://youtrack.jetbrains.com/issue/KT-3110

查看更多
登录 后发表回答