Single Instance Enums (Enum Object)


It’s mostly a QOL suggestion, but there have been times where I only needed a single instance of a enum class.

I propose enum object as a single instanced enum class.


Enum values are already single instances of the value so you can have an enum with a single value. Alternatively you can have singleton objects. So it isn’t clear what you are proposing.


Instead of:

enum class GlobalState { ONGOING, WIN, LOSE, DRAW }
var state = GlobalState.ONGOING
if (state == GlobalState.ONGOING) state = GlobalState.DRAW

I’m suggesting to:

enum object GlobalState { ONGOING, WIN, LOSE, DRAW } = GlobalState.ONGOING
if (GlobalState == GlobalState.ONGOING) GlobalState = GlobalSate.DRAW

If they do implement the feature of short notation for enum constants, then it works out even more to:

enum object GlobalState { ONGOING, WIN, LOSE, DRAW } = ONGOING
if (GlobalState == ONGOING) GlobalState = DRAW


You mean like in C++ where the Enum type name is not needed when the context makes clear what it is (without poluting the namespace like C style enums do)? I can see where not writing the enum type name is useful, but I would say introducing a separate type for that is unneeded (regular Kotlin enums are not integers in disguise - like C enums), it could just be a change in the language grammar (with appropriate ambiguity/priority rules).


What is the state in the proposed variant?


Sorry, miswrote. I was using my phone and copy-pasted the previous block and forgot to edit the proper parts.

I have editted it to reflect how I meant to be.


I don’t like it. It mixes 2 different purposes. It makes GlobalState into a type as well as a variable of its own type. Also, the primary use case for it, provided by the example’s name, is generally considered a bad thing.


Aren’t Objects both a type and a variable on its own as well? How would an enum object differ.

I used a poor example, but I still stand that it has its uses.

class TrafficLight {
    enum class Light { RED, YELLOW, GREEN }
    var light = Light.RED


class TrafficLight {
    enum object Light { RED, YELLOW, GREEN } = Light.RED


Yes, but objects can be stateless (and should be). What you’re proposing is solely for creating global state.

Your last example there is confusing. I think that you mean to have a single instance per instance of Traffic light, but that’s not what it seems like.