Kotlin: How to extend the enum class with an extension function

geg picture geg · Mar 13, 2016 · Viewed 13.8k times · Source

I'm trying to extend enum classes of type String with the following function but am unable to use it at the call site like so:

fun <T: Enum<String>> Class<T>.join(skipFirst: Int = 0, skipLast: Int = 0): String {
    return this.enumConstants
        .drop(skipFirst)
        .dropLast(skipLast)
        .map { e -> e.name }
        .joinToString()
}

MyStringEnum.join(1, 1);

What am I doing wrong here?

Answer

Ruslan picture Ruslan · Mar 13, 2016

I suggest following solution:

fun <T : Enum<*>> KClass<T>.join(skipFirst: Int = 0, skipLast: Int = 0): String {
    return this.java
            .enumConstants
            .drop(skipFirst)
            .dropLast(skipLast)
            .map { e -> e.name }
            .joinToString()
}

Instead of attaching extension function to Class, i attached it to KotlinClass.

Now, you can simply use it:

enum class Test {ONE, TWO, THREE }

fun main(args: Array<String>) {
    println(Test::class.join())
}
// ONE, TWO, THREE