How to Create `Array<out T?>?`?


#1

I'm programming with LibGDX, a game framework. To create an animation, I have to fullfill either of these signatures:

Animation(frameDuration: Float, frames: Array<out TextureRegion?>?)

Animation(frameDuration: Float, frames: vararg TextureRegion?)

The problem:  I have multiple animations that I “cut” out of a sprite sheet. They’re numbered sequentially like so

val walkingAnimation = Animation(0.2f,

           atlas.findRegion("4"),

           atlas.findRegion("5"),

           atlas.findRegion("6"),

           atlas.findRegion("7")

  )

And now I’d like to write a generic function

private fun createAnimation(from: Int, to: Int, playMode: PlayMode) {

  val atlas = assetManager.get("atlas/Goku/Goku.atlas", javaClass<TextureAtlas>())!!

  val frames = (from..to).map { atlas.findRegion(it.toString()) }

  return Animation(0.2f, frames) // Error, frames is of incorrect type

  }

I have also tried the splat operator (*frames) and typing the frames variable:

val frames: List<TextureRegion?> = (from..to).map { atlas.findRegion(it.toString()) }

return Animation(0.2f, *frames)

So now I turn to you, dear Kotlin community. I’m obviously doing something wrong, but what? I’m sure there’s an easy solution, but I just can’t figure it out :frowning:


#2

Hi, Christian!

Your problem is that the function map returns the List, but you need Array. You can fix it using copyToArray, like:

val frames = (from…to).map { atlas.findRegion(it.toString()) }.copyToArray()