简体   繁体   中英

How to create an array of Abstract class in Kotlin Without inheriting the abstract class

I have 2 classes, class A which is an abstract class, and a class B like

abstract class A(name: String){
    //some code
}

class B {
    //some code
}

Now if I want to add and array of type class A in Class B it is very simple in java like

class B {
    A[][] arr = new A[2][2];
}

but I am trying the same in Kotlin like

class B { 
    var arr = Array(2) {Array(2) {A}}
}

then it is giving error as "Classifier 'A' does not have a companion object and thus must be initialized here" but then I tried putting some variables in the companion object in the abstract class, and now it does not give any error. but the array is made of type 'A.companion' and not of type 'A'.

Kindly help me if you know anything about this.

Your Java code creates an array of 2 arrays, each of which can hold 2 objects of type A or null and initially contains null. (In Java, every reference value is nullable, so this is standard practice.)

The Kotlin equivalent of that is:

Array(2){ Array(2){ null as A? }}

Like the Java code, each element there is nullable, and is initialised to null.

(The error you're getting is because you're trying to give the Array constructor a type, but it's expecting a value — so it's trying to interpret A as a value, and guessing you mean the companion object of A . Don't worry if you don't know what that is!)

However, Kotlin supports non-nullable values too, which are often preferable. So if you know what values you want the array to hold, it's more common to create and initialise it in one go, so that the type can be non-nullable. For example:

arrayOf(arrayOf(A("1"), A("2")),
        arrayOf(A("3"), A("4")))

Notice that in Java, the array created by new A[2][2] contains only null elements. There are no instances of A s in there. In Kotlin, this would be represented as a Array<Array<A?>> , rather than Array<Array<A>> , because the A s are null initially.

In terms of one dimensional arrays, you essentially have an array of 2 elements, and each of those is an array of 2 elements containing nulls only. Hence, you can write:

val aArray = Array<Array<A?>>(2) { arrayOfNulls(2) }

or a little bit shorter:

val aArray = Array(2) { arrayOfNulls<A>(2) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM