Enum class with type parameters

To have a logically related iterable set of objects (without having to use reflection) I just wrote the following helper base class:

open class EnumObjectList<T> private constructor( private val list: MutableList<T> ) :
    List<T> by list
{
    constructor() : this( mutableListOf() )

    protected fun <TAdd : T> add( item: TAdd ): TAdd = item.also { list.add( it ) }
}

Which for example can be used as follows:

object SamplingSchemes : EnumObjectList<DataTypeSamplingScheme<*>>()
{
    val GEOLOCATION = add( Geolocation( TimeSpan.fromMinutes( 1.0 ) ) )
    val STEPCOUNT = add( Stepcount( TimeSpan.fromMinutes( 1.0 ) ) )
}

The members retain their full type information, and there is no need for an ‘intermediate’ enum type.

3 Likes