我有一个接口,我想要一个可以在类内部修改但不能在外部修改的属性.我不能使用val,因为它需要是可变的,并且var关键字不能有指定的私有setter,因为它在接口中.
In Java I would have done this:
public <T> getMyProperty();
我可以在Kotlin中使用相同的方法,只需直接编写getter函数,但这看起来不像是一种类似Kotlin的方法.有没有更好的方法来实现同样的目标呢?
fun getMyProperty()
我有一个接口,我想要一个可以在类内部修改但不能在外部修改的属性.我不能使用val,因为它需要是可变的,并且var关键字不能有指定的私有setter,因为它在接口中.
In Java I would have done this:
public <T> getMyProperty();
我可以在Kotlin中使用相同的方法,只需直接编写getter函数,但这看起来不像是一种类似Kotlin的方法.有没有更好的方法来实现同样的目标呢?
fun getMyProperty()
In Kotlin, you can actually override
a val
with a var
, so, I think, what you want can be expressed as follows:
interface Iface {
val foo: Foo
}
class Impl : Iface {
override var foo: Foo
get() = TODO()
private set(value) { TODO() }
}
或者,您可以使用带有后备字段和默认访问器的属性覆盖val
:
class ImplDefaultGetter : Iface {
override var foo: Foo = someFoo
private set
}
In both cases, the mutability and the presence of a private setter become an implementation detail of the classes and are not exposed through the interface.