Search code examples
inheritancekotlinencapsulationgetter-setteraccess-modifiers

"public read-only" access modifier?


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


Solution

  • 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()
    }