Search code examples
genericsenumskotlinextension-methodscompanion-object

How to declare extension parameter on generic enums companions


I'd like to have .MAX on generic enums to represent the values count.

I tried to play a little but I couldn't figure it out.

When I write, for example, this:

val Enum.Companion.MAX get() = enumValues().size

It complains on enumValues() that

Type inference failed: Not enough information to infer parameter T in

inline fun > enumValues ( ) : Array Please specify it explicitly.

It makes sense, then I tried also:

val <E> Enum<E>.Companion.MAX get() = enumValues().size

It complains on the second E

Type arguments for outer class are redundant when nested class is referenced

Is there a way?


Solution

  • You have to use a reified type parameter so that the actual enum type is used at each call site:

    inline val <reified T : Enum<T>> T.MAX get() = enumValues<T>().size