https://kotlinlang.org logo
Title
f

Fudge

06/29/2019, 6:30 AM
Is there a way to add a method to an enum class without reflection? If I have
enum class Test{
foo
}
Then kotlin comes built in with
values(), valueOf()
, but how can I add a new helper method like
getValueNames()
?
g

gildor

06/29/2019, 7:05 AM
Do you need Test.getValueNames?
You can use companion object for this, same for any other class
f

Fudge

06/29/2019, 9:10 AM
Yes but I want it to work polymorphicly
kotlin
interface SecondName{
   val str : String
}

enum Test(override val str : String) : SecondName{
One(“1”),Two(“2”)
}

//and then do something like 
fun <T>class<T>.allSecondNames() where T: SecondName, T: Enum<T>{
return values().map{it.str}
}

//and then do
val names = Test.allSecondNames()
g

gildor

06/29/2019, 10:28 AM
Which is pretty different from you original question
Honestly I don't like this approach that requires this complicated polymorphism with enum and interface, are you sure that you really need this for enum? Maybe just extension for Collection<SecondName> would be enough?