https://kotlinlang.org logo
Title
e

Erfan

05/07/2018, 1:00 PM
hi, how to create an empty generic array in Kotlin?
var items: Array<T> = ?
I wanted to use
arrayOf<T>()
but this doesn't work.
a

Andreas Sinz

05/07/2018, 1:17 PM
@Erfan You need to tell the compiler what
T
is
e

Erfan

05/07/2018, 1:20 PM
how do I do it? It's not known at compile time.
i.e: it could be almost any type
a

Andreas Sinz

05/07/2018, 1:22 PM
then use
Any
r

rrader

05/07/2018, 1:26 PM
var items: Array<T> = emptyArray()
e

Erfan

05/07/2018, 1:26 PM
it responds with
Type mismatch
when I try to do :
var items: Array<T> = arrayOf<Any>()
a

Andreas Sinz

05/07/2018, 1:27 PM
you cannot use an undefined
T
in your code, you need to use
Array<Any> = arrayOf()
s

spand

05/07/2018, 1:27 PM
Cant you just cast it ?
a

Andreas Sinz

05/07/2018, 1:28 PM
Array is invariant, so no
your best option is to use
Any
and cast the items where necessary
e

Erfan

05/07/2018, 1:31 PM
more complete code of the situation is this:
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

Andreas Sinz

05/07/2018, 1:32 PM
does
class ...(var items: Array<T> = emptyArray(), ...
work?
s

spand

05/07/2018, 1:32 PM
class Foo<T> {
    val foo: Array<T> = Array<Any?>(0, {}) as Array<T>
}
works just fine. Its just an unchecked cast
a

Andreas Sinz

05/07/2018, 1:33 PM
@spand in your example
T
is known. I was suspecting that he had a
Array<T>
inside a non-generic class
d

diesieben07

05/07/2018, 1:34 PM
This comes down to: Don't use an
Array<T>
, use
List<T>
. "Because Java" array-generics behave differently than everywhere else.
e

Erfan

05/07/2018, 1:34 PM
@Andreas Sinz nope, doesn't work
s

spand

05/07/2018, 1:35 PM
...
Anyways.. @diesieben07 is right
e

Erfan

05/07/2018, 1:42 PM
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.
:trollface: 1