hi ```fun main() { val arrayB:Array<B> =...
# getting-started
g
hi
Copy code
fun main() {
   val arrayB:Array<B> = arrayOf(B())
   val arrayA:Array<A> = arrayB
   val arrayA2:Array<A> = arrayOf(B())

}

open class A()
class B: A()
why second line gives error but third doesnt? i know that arrays are invariant but then why it's okay with the 3rd line?
g
Because
Array
is not covariant, so you cannot cast
Array<B>
to
Array<B>
. But at the same time you can cast all elements of type
B
to type
A
, which is done with every element in
arrayOf(...)
in the third line. Another way to see the problem is that when you have
Array<B>
you cannot expose it as
Array<A>
, otherwise one can put element of type
A
in it which is prohibited. However, having a bunch (don't know how to say "collection" not referring
Collection
interface) of elements of type
B
, one can say that it is a bunch of elements of type
A
. That's why
vararg
arguments are of type
Array<out E>
instead of
Array<E>
.
m
If you replace the third line with
val array:A2:Array<A> = arrayOf<B>(B())
you would get the failure, but the compiler is translating it to ``val arrayA2Array<A> = arrayOf<BA>(B())` which is allowed
2
g
so it converts every B object to A implicitly before assigning it to to the array?
m
Converts the B reference to an A reference, the object is still a B
g
okay, i think i got it
thanks @Gleb Minaev @Michael Krussel. much appreciated!