Hi, I have a basic question. Can you hand me a lin...
# announcements
j
Hi, I have a basic question. Can you hand me a link that explains the data type hierarchy when declaring a variable? Lets say I have:
Copy code
val list = mutableListOf<String>()
variable
list
will be a mutable list. but if I have
Copy code
val list: List<String> = mutableListOf<String>()
variable
list
will be an immutable list. Can someone explain the hierarchy here? Is the defined variable data type always becomes the winning data type?
d
The 2nd list is not immutable. You could still do a cast to
MutableList
and modify it.
List
is simply an interface that does not allow modification of the List, but it does not mean the object is actually immutable.
😲 1
🤯 1
m
MutableList (the real type of objects you get from calling mutableListOf) is a subtype of List. So all mutable lists are actually just lists with additional methods for modifying the list, and can be used where an immutable list (so a List object) is expected. I'm not sure if that was clear.
d
Again,
List
is not immutable
It is read only
t
the interface is simply YOUR view on the data. even without casting, someone else could change the collection although your view doesnt allow mutations
3
d
There is a very important difference
j
Yes! All clear @diesieben07 & @thana Thanks!
& @Matthieu Stombellini
c
using
list
you can only invoke functions of
List<String>
👍 1