Granular getter / setters on properties in interfaces


#1

Hi,

I’m currently porting something from Java to Kotlin.

In Java, I have an interface that contains a getter, and not a setter, and I have classes that implement the interface, all classes implement the getter, and some classes provide a setter.

As I try to think about porting this, the problem I have is how to map this to a property in Kotlin.

If I put the property in the interface then it implies that everything that implements the interface has to implement a full property, with getter and setter. And I don’t know how to specify a half property (getter only) in the interface in such a way that a fully defined property (in the implementation classes) would not be flagged as not matching up to the interface.

In Java, it was quite easy. A getter and setter are seperate. In Kotlin, because the getter and setter share a property, I don’t know how to do this without getting hackish.

Best practise advice much appreciated.


#2

You can use “private set”

var foo : String = ""
   private set

Or you can create a val

val foo : String
   get() {  
    //TODO
}

#3

If you put a val property in the interface, this only requires implementations of the interface to provide a getter. They can override a val property with a var, if they need a setter too. The effect is exactly the same as with Java.