hi, how to create an empty generic array in Kotlin...
# announcements
e
hi, how to create an empty generic array in Kotlin?
Copy code
var items: Array<T> = ?
I wanted to use
arrayOf<T>()
but this doesn't work.
a
@Erfan You need to tell the compiler what
T
is
e
how do I do it? It's not known at compile time.
i.e: it could be almost any type
a
then use
Any
r
var items: Array<T> = emptyArray()
e
it responds with
Type mismatch
when I try to do :
Copy code
var items: Array<T> = arrayOf<Any>()
a
you cannot use an undefined
T
in your code, you need to use
Array<Any> = arrayOf()
s
Cant you just cast it ?
a
Array is invariant, so no
your best option is to use
Any
and cast the items where necessary
e
more complete code of the situation is this:
Copy code
class PaginationManager<T>(var items: Array<T>,
                           var totalCount: Int,
                           val pageSize: Int,
                           var pageNumber: Int,
                           var status: PaginationStatus = PaginationStatus.WaitingForNextPageTrigger,
                           private val fetchClosure: PaginationFetchClosure<T>)
I just wanted to have default empty array for that. Now I set an empty array of known type, in the call site.
I had implemented something similar in Swift with no problem, so that's what made me wondering about something similar in Kotlin
a
does
class ...(var items: Array<T> = emptyArray(), ...
work?
s
Copy code
class Foo<T> {
    val foo: Array<T> = Array<Any?>(0, {}) as Array<T>
}
works just fine. Its just an unchecked cast
a
@spand in your example
T
is known. I was suspecting that he had a
Array<T>
inside a non-generic class
d
This comes down to: Don't use an
Array<T>
, use
List<T>
. "Because Java" array-generics behave differently than everywhere else.
e
@Andreas Sinz nope, doesn't work
s
...
Anyways.. @diesieben07 is right
e
thanks everyone, yes @diesieben07's right
was not aware of the limitation
you guys don't want to set a profile picture? 😄 I mean look at the thread.. it's a bit difficult to follow who said what.
🧌 1