Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to add an abstract private getter and a public setter?

Tags:

kotlin

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()
like image 489
Henrik F. Avatar asked Jun 26 '17 17:06

Henrik F.


People also ask

Can you use getters and setters in an abstract class?

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.

Is getter setter an abstraction?

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.

Are getters and setters always public?

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.


1 Answers

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.

like image 120
hotkey Avatar answered Oct 01 '22 06:10

hotkey