I have an interface where I want a property that can be modified innside the class, but not outside. I cannot use val because it needs to be mutable and the var keyword can not have a specified private setter since this is in an interface.
In Java I would have done this:
public <T> getMyProperty();
I can use the same approach in kotlin and just write the getter function dirrectly, but this does not seem like a kotlinlike approach. Is there a better way to achieve the same as this?
fun getMyProperty()
You can do everything in an abstract class that you can do in a normal class except creating a new object only by using a constructor. This means that you can simply copy and paste the getters and setters from your subclass into your parent class.
With getters and setters, we achieve one more key principle of OOP, i.e., abstraction, which is hiding implementation details so that no one can use the fields directly in other classes or modules.
It depends on your requirement and design. Generally, it getter and setters are made public to provide acess to other classes. Looking it, at your class and constructor , i believe you don't want to provide outside class acess, so keepthem private.
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() }
}
Or you can override the val
with a property with a backing field and default accessors:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With