Gamar Mustafa
10/29/2024, 12:34 PMfun 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?Gleb Minaev
10/29/2024, 12:56 PMArray 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>.Michael Krussel
10/29/2024, 1:03 PMval 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 allowedGamar Mustafa
10/29/2024, 1:04 PMMichael Krussel
10/29/2024, 1:05 PMGamar Mustafa
10/29/2024, 1:06 PMGamar Mustafa
10/29/2024, 1:06 PM