【问题标题】:"public read-only" access modifier?“公共只读”访问修饰符?
【发布时间】:2019-07-15 09:52:57
【问题描述】:

“传统”实现:

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】:

    无法将接口成员的可见性限制为protected

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-11
      • 2011-01-31
      • 2017-08-11
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      相关资源
      最近更新 更多