1

"traditional" implementation:

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

What I'd like, now, would be something like this:

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

I have a hunch the answer is going to be no, but ...

Any way to make this happen?

User1291
  • 7,664
  • 8
  • 51
  • 108

1 Answers1

2

There's no way to restrict an interface member visibility to protected.

However, you can define a val in the interface and override it with a var in the implementations:

interface IFoo {
    val s: String
}

class Foo : IFoo {
    override var s = "bar"
        protected set
        get() = field.toUpperCase()
}
hotkey
  • 140,743
  • 39
  • 371
  • 326