“传统”实施:
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"
}}
}
我有预感,答案是否定的,但......
有没有办法实现这一目标?
没有办法限制接口成员对protected
的可见性。
但是,您可以在接口中定义val
,在实现中定义override it with a var
:
interface IFoo {
val s: String
}
class Foo : IFoo {
override var s = "bar"
protected set
get() = field.toUpperCase()
}