#getting-started
Title
# getting-started
l

LastExceed

04/16/2022, 9:59 AM
why can i do
Copy code
``````val x: List<Int> = listOf(1, 2, 3)
val y: List<Number> = x //works fine``````
but not
Copy code
``````val x: Array<Int> = arrayOf(1, 2, 3)
val y: Array<Number> = x //error: type mismatch``````
?
r

Rick Clephas

04/16/2022, 10:09 AM
This is due to the generic variance: https://kotlinlang.org/docs/generics.html#variance List is defined as
``List<out E>``
and Array as
``Array<T>``
. In your example list can only return
``Int``
elements. So this allows the cast to
``Number``
since every
``Int``
is also a
``Number``
. Array however also accepts elements (e.g. in the
``set``
function). Since it expects an
``Int``
in these functions you won't be able to cast the array to
``Number``
. This is because while all `Int`s are `Number`s not all `Number`s are `Int`s.
l

LastExceed

04/16/2022, 10:11 AM
Array however also accepts elements
i dont understand this part, what does
``element``
mean exactly?
r

Rick Clephas

04/16/2022, 10:17 AM
With element I mean an item in the array or list. So in your example
``1``
,
``2``
and
``3``
are the elements.
l

LastExceed

04/16/2022, 10:18 AM
but then what is the sentence
Array however also accepts elements
supposed to mean? it kinda implies that lists dont accept elements which makes no sense
r

Rick Clephas

04/16/2022, 10:22 AM
Yeah a
``List``
is immutable. So you can't add more elements to it (if you want to add elements to a list you would need a
``MutableList``
).
``Array``
however does allow you to update the elements with the
``set``
function.
l

LastExceed

04/16/2022, 10:24 AM
oooh thats what you meant. got it ty
👍🏻 1
3 Views