Kotlin: arrayOfNulls() with generic type


Topics interesting only for Kotlin / Android / SQLite programmers

Link to this posting

Postby Ursego » 31 Dec 2019, 20:28

If you write

Code: Select all
val arr = arrayOfNulls<T>(5)

you get a compilation error "Cannot use 'T' as reified typealias parameter. Use a class instead.".

Solution: In your "util" package, create the global function genericArrayOfNulls():

Code: Select all
@Suppress("UNCHECKED_CAST")
fun <T> genericArrayOfNulls(size: Int): Array<T?> = arrayOfNulls<Any?>(size) as Array<T?>


Now, you can use it instead of arrayOfNulls():

Code: Select all
val arr = genericArrayOfNulls(5)
User avatar
Ursego
Site Admin
 
Posts: 139
Joined: 19 Feb 2013, 20:33



IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
Traffic Counter

free counters

eXTReMe Tracker