nilTheDev
07/15/2021, 3:50 PMclass Dummy{
private val _data = mutableListOf<Int>()
val data:ListOf<Int> = _data
}
class Dummy{
private val _data = mutableListOf<Int>()
val data: ListOf<Int>
get() = _data
Thanks for your help.Tobias Berger
07/15/2021, 4:00 PM_data
during initialization, so your class has 2 instances of the same object.
In the second one, data
is just a "virtual" property with a getter but no underlying field. if you access it, it will just return the value currently stored in _data
Tobias Berger
07/15/2021, 4:02 PM_data
is an immutable property (= no setter) the behaviour is basically identical between the versions, you just have an additional reference to the same object in version 1. But if _data
was a var
instead of val
, the first version would not "react" to changes while the second one always gives you the updated value.Tobias Berger
07/15/2021, 4:07 PMpublic class Dummy {
private final List<Integer> data;
private final List<Integer> _data;
public Dummy() {
_data = new ArrayList();
data = _data;
}
public List<Integer> getData() {
return data;
}
}
v2:
public class Dummy {
private final List<Integer> _data;
public Dummy() {
_data = new ArrayList();
}
public List<Integer> getData() {
return _data;
}
}
nschulzke
07/15/2021, 4:07 PMvar
with the first snippet is that it would react to some changes but not others. If all you were doing was adding items to the list, everything would be as expected. But if you assign a new list to the var
(_data = [something else]
), data
would still be pointing to the old list, and would not follow _data
to the new list. So from that point on it would no longer track changes.
As a rule, I prefer to use the second version, because it makes it explicit that data
is just an immutable alias for _data
.nilTheDev
07/15/2021, 4:24 PMvar
version.