What would be the difference between the following...
# announcements
n
What would be the difference between the following code snippets?
Copy code
class Dummy{
    private val _data = mutableListOf<Int>()
    val data:ListOf<Int> = _data
}
Copy code
class Dummy{
    private val _data = mutableListOf<Int>()
    val data: ListOf<Int>
        get() = _data
Thanks for your help.
t
The first one creates an actual field that is assigned the value of
_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
❤️ 2
because
_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.
❤️ 1
this is how these classes would look in Java, maybe that helps with understanding the difference. v1:
Copy code
public 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:
Copy code
public class Dummy {
    private final List<Integer> _data;

    public Dummy() {
        _data = new ArrayList();
    }

    public List<Integer> getData() {
        return _data;
    }
}
👍 2
n
The tricky thing with using
var
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
.
❤️ 1
n
@Tobias Berger @nschulzke Great. Thank you so much. It makes perfect sense! Even though I previously understood that in the first version an extra reference to the same object would be created but I haven't considered the
var
version.