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

Viewed 19080

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?

4 Answers

Use of ::class is a nasty workaround. I suggest you to look at enumValues<E> and enumValueOf<E> from stdlib and do the same way:

inline fun <reified E : Enum<E>> joinValuesOf(skipFirst: Int = 0, skipLast: Int = 0): String =
        enumValues<E>().join(skipFirst, skipLast)

@PublishedApi
internal fun Array<out Enum<*>>.join(skipFirst: Int, skipLast: Int): String =
        asList()
                .subList(skipFirst, size - skipLast)
                .joinToString(transform = Enum<*>::name)

Usage: joinValuesOf<Thread.State>()

Related