How to declare extension parameter on generic enums companions

1.8k views Asked by At

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?

2

There are 2 answers

0
hotkey On BEST ANSWER

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
0
Gibolt On

Extend a generic Enum with a reified type

inline fun <reified T : Enum<T>> max(): Int = enumValues<T>().size

// Then call
max<MyEnum>()

Alternatively, you can add it to an instance of the enum

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

// Then call
MyEnum.VALUE.max // or myEnumVal.max