mercredi 18 mai 2022

Best practice for exposed fields in Kotlin

I have often the problem that I want to use a mutable class inside, but I don't want to expose the mutable interface. Here are two samples:

class Sample {
    val listData: List<Any> = mutableListOf()
    val liveData: LiveData<Any> = MutableLiveData()

    fun updateFields() {
        // update both fields above: The add() and postValue() methods are not visible here
    }
}

I'm casting the fields sometimes other times I use private extension functions/properties. In rare cases I also used two fields one private with the mutable interface and the public with the immutable interface. The first two options feel very hacky and look ugly the last one with the second property feels very redundant and like the "normal" java boilerplate.

Another option would be to define an interface where just the implementation has the mutable fields, but that is again boilerplate which I want to avoid. How do you handle this?

Aucun commentaire:

Enregistrer un commentaire