https://kotlinlang.org logo
#announcements
Title
# announcements
j

jermainedilao

08/08/2019, 7:51 AM
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

diesieben07

08/08/2019, 7:53 AM
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

Matthieu Stombellini

08/08/2019, 7:56 AM
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

diesieben07

08/08/2019, 7:56 AM
Again,
List
is not immutable
It is read only
t

thana

08/08/2019, 7:56 AM
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

diesieben07

08/08/2019, 7:56 AM
There is a very important difference
j

jermainedilao

08/08/2019, 7:57 AM
Yes! All clear @diesieben07 & @thana Thanks!
& @Matthieu Stombellini
c

corneil

08/08/2019, 8:42 AM
using
list
you can only invoke functions of
List<String>
👍 1
2 Views