“public read-only”访问修饰符?

问题描述 投票:1回答:1

“传统”实施:

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

我有预感,答案是否定的,但......

有没有办法实现这一目标?

inheritance kotlin encapsulation getter-setter access-modifiers
1个回答
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()
}
© www.soinside.com 2019 - 2024. All rights reserved.