Search code examples
androidfunctionkotlinparametersenums

Android Kotlin - Enum Class as parameter of a function


I have several ENUMs in the following format:

enum class MyEnum1(val id: Int, val titleId: Int) {
    A1(0, R.string.a1),
    B1(1, R.string.b1),
    ...
}

enum class MyEnum2(val id: Int, val titleId: Int) {
    A2(0, R.string.a2),
    B2(1, R.string.b2),
    ...
}

I also have a Compose dialog, that lists these values, but now I have all these enums first converted to List<Pair<Int,Int>> before I give it to my dialog component, as a parameter.

How would it be possible to make the Compose function have a parameter of any Enum class type? I'd like to call my Composable like so:

ListDialog( ..., enum = MyEnum1::class, ...)
also
ListDialog( ..., enum = MyEnum2::class, ...)

then process my data:

for (item in enum.values()) {
        // something
    }

Solution

  • I don't really have experience with Compose so I'm not sure how that all works, but I have experience with kotlin in general. And what you could do is have all your enums implement a common interface. Then this is possible for example:

    fun main() {
        test(MyEnum1.values())
        test(MyEnum2.values())
    }
    
    fun test(enum: Array<out EnumsWithIdAndTitle>){
        for (item in enum) {
            println(item.titleId)
        }
    }
    
    interface EnumsWithIdAndTitle {
        val id: Int
        val titleId: Int
    }
    
    enum class MyEnum1(override val id: Int, override val titleId: Int) : EnumsWithIdAndTitle  {
        A1(0, 11),
        B1(1, 22),
    }
    
    enum class MyEnum2(override val id: Int, override val titleId: Int) : EnumsWithIdAndTitle {
        A2(0, 33),
        B2(1, 44),
    }
    

    then instead of my test function you could modify your ListDialog in a similar way I think