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: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker