Category: Kotlin

Suppose you have a list of object instances (Kotlin’s concept for singleton classes) that are logically related to one another and you therefore want to group them together, but also want to provide direct (non-index- or iterator-based) access to them, similar to how you access an enum.

How would you go about doing that in Kotlin?

As an example, take the following DataType interface and implementing object Geolocation:

Imagine many more DataType‘s: WeightType, StepcountType, etc. Now you want to provide a list of SupportedTypes containing all the types your codebase supports, but you also want to provide direct access to that list, so that the create() method (and other potential type-specific members) for Geolocation can be called.

While enums in Kotlin are fairly powerful—they largely behave like normal classes and can implement interfaces—they do not support generic type parameters and (as far as I could figure out) enum values cannot be instantiated based on existing instances. You could let the enum implement the interface of the instances you want to represent and override all methods redirecting them to the wrapped instance, but:

This introduces an intermediate instance, which might not be desirable for equality checking.

Does not provide access to type-specific members, such as create() in the example given.