I'm new in Kotlin, but I have a lot of experience with Java.
Little background of the question... I have a class with a MutableList property there.
class ModesAdapter(val modes : MutableList<Mode> = mutableListOf()) : RecyclerView.Adapter<ModeViewHolder>()
And I want to be able to set this propery, but to forbid (or restrict) a get operation. In Java it would be like:
class ModesAdapter extends RecyclerView.Adapter<ModeViewHolder>{
private final List<Mode> modes;
public ModesAdapter() {
modes = new ArrayList<Mode>();
}
public ModesAdapter(List<Mode> modes) {
this.modes = modes;
}
public void updateModes(List<Mode> modes) {
this.modes.clear();
this.modes.addAll(modes);
notifyDatasetChanged();
}
}
For Kotlin I have two possible options.
Option #1. Use Kotlin provided get/set methods + backing property. In this case I need to override a get method to return immutable list.
class ModesAdapter(modes : MutableList<Mode> = mutableListOf()) : RecyclerView.Adapter<ModeViewHolder>(){
private val _modes : MutableList<Mode> = modes
var modes : List<Mode>
get() = _modes.toList()
set(value) {
_modes.clear()
_modes.addAll(value)
notifyDataSetChanged()
}
}
Ideally, I have to remove get
at all or make it private, but I cannot do this because of visibility of var modes
. To update modes now I just need to:
val modesAdapter = ModesAdapter()
modesAdapter.modes = mutableListOf<Mode>(Mode("Mode 1"))
Option #2. Just throw away all Kotlin's stuff and use "Java approach".
class ModesAdapter(private val modes : MutableList<Mode> = mutableListOf()) : RecyclerView.Adapter<ModeViewHolder>(){
fun updateModes(modes : List<Mode>) {
this.modes.clear()
this.modes.addAll(modes)
notifyDataSetChanged()
}
To access modes in this case I need to:
val modesAdapter = ModesAdapter()
modesAdapter.updateModes(mutableListOf<Mode>(Mode("Mode 1")))
Maybe the second approach is cleaner and has less lines of code, but the first one looks more "Kotlin-style": we have a property and separate setter/getter for it.
So what's the correct way to achieve the behavior described above from the ideological point of view in Kotlin? May be you can suggest your own correct option (it would be nice, by the way).