LastExceed
04/16/2022, 9:59 AMval x: List<Int> = listOf(1, 2, 3)
val y: List<Number> = x //works fine
but not
val x: Array<Int> = arrayOf(1, 2, 3)
val y: Array<Number> = x //error: type mismatch
?Rick Clephas
04/16/2022, 10:09 AMList<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.LastExceed
04/16/2022, 10:11 AMArray however also accepts elementsi dont understand this part, what does
element
mean exactly?Rick Clephas
04/16/2022, 10:17 AM1
, 2
and 3
are the elements.LastExceed
04/16/2022, 10:18 AMArray however also accepts elementssupposed to mean? it kinda implies that lists dont accept elements which makes no sense
Rick Clephas
04/16/2022, 10:22 AMList
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.LastExceed
04/16/2022, 10:24 AM