https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Pitel

08/19/2021, 11:33 AM
I have many `enum`s with the following prototype:
enum class SomeHeaders(val label: String)
(for headers of different tables). How can I write a type parameter (like
val a: ???WHAT???
) so that it will be clear that it's
enum
(so I can use
values()
, etc.) and it had the
label
parameter. The parameter has easty solution: interface, but what about the
enum
limitation?
r

Roukanken

08/19/2021, 12:04 PM
something like this seems to work, with generics:
Copy code
interface Labeled {
    val label: String
}

enum class LabeledEnum(override val label: String): Labeled {
    THE_ONE("the one")
}

data class LabeledClass(override val label: String): Labeled

fun <T> test(a: T) where T: Enum<T>, T: Labeled {
    println(a)
}

fun main() {
    test(LabeledEnum.THE_ONE)
    test(LabeledClass("not the one")) // this line does not compile
}
without generics it would need so called intersection types, usually written as
Enum<T> & Labeled
or similarly, sadly Kotlin does not have these, nor there are any plans for them so far
for
values()
you could use
enumValues<T>()
but that would need to be inside reified inline function
p

Pitel

08/19/2021, 12:44 PM
Tahnk, TIL there is a
where
keyword exactly for this 👍🏻
@Roukanken Hmm, but that's still not it. I want to do
test(LabeledEnum)
, like, pass the whole enum, not just single value.
2 Views