“公共只读”访问修饰符?

时间:2019-02-21 13:06:00

标签: inheritance kotlin encapsulation getter-setter access-modifiers

“传统”实施方式:

interface IFoo{
    fun getS():String
    fun modifyS():Unit
}

class Foo : IFoo{
    private var s = "bar"

    override fun getS() = s.toUpperCase()
    override fun modifyS(){ s = when(s){
        "bar" -> "baz"
        else -> "bar"
    }}
}

现在我想要的是这样的

interface IFoo{
    var s:String
        protected set

    fun modifyS():Unit
}

class Foo : IFoo{
    override var s = "bar"
        protected set
        get() = field.toUpperCase()

    override fun modifyS(){ s = when(s){
        "bar" -> "baz"
        else -> "bar"
    }}
}

我有一个预感,答案是“否”,但是...

有什么办法做到这一点?

1 个答案:

答案 0 :(得分:2)

无法将界面成员的可见性限制为protected

但是,您可以在接口中定义val,在实现中定义override it with a var

interface IFoo {
    val s: String
}

class Foo : IFoo {
    override var s = "bar"
        protected set
        get() = field.toUpperCase()
}