lundi 14 décembre 2020

How to pass vararg of different classes that inherit another class in Kotlin?

I'm trying to create a simple game in Kotlin. I have a BitmapContainer class which is inherited by another classes. Inheritors has init block and companion objects which contains list of bitmaps, so that they created once and used for all objets of the same type.

What I want is to create BitmapPreloader class, which has a vararg of BitmapContainer-derived classes and a callback. Preloader should create one instance of every class in vararg and invoke callback method.

The question is: how to pass classes that way? I just can't figure it out.

I don't know if it will be of help, but here's some of described code:

abstract class BitmapContainer(
val res: Resources,
val downScale: Float,
val onInitializationCompletedListener: (() -> Unit)? = null) {
protected fun createBitmap(
    @DrawableRes resId: Int,
    useFilter: Boolean = false
): Bitmap {
    BitmapFactory.decodeResource(res, resId).also {
        return Bitmap.createScaledBitmap(
            it,
            (it.width / downScale * Screen.ratioX).toInt(),
            (it.height / downScale * Screen.ratioY).toInt(),
            useFilter
        )
    }
}

protected fun createBitmapList(
    resIds: List<Int>,
    useFilter: Boolean = false
): List<Bitmap> = ArrayList<Bitmap>().apply {
    resIds.forEach {
        this.add(createBitmap(it, useFilter))
    }
}

BitmapContainer example:

class GroundTileBitmapContainer(
res: Resources,
downScale: Float,
listener: (() -> Unit)? = null) : BitmapContainer(res, downScale, listener) {

init {
    if (bitmap == null) {
        bitmap = createBitmap(R.drawable.ground_02)
    }
}

companion object {
    var bitmap: Bitmap? = null
}

}

What I want to do in Preloader:

lass BitmapPreloader(
vararg classList: Any?, //That is the line I have no idea how to do
callback: () -> Unit) {

init {
    classList.forEach { it::class.createInstance() }
    callback.invoke()
}




Aucun commentaire:

Enregistrer un commentaire