Reduce enum verbosity

Hi everyone, I was wondering how difficult will be implement into Kotlin some Swift sugar related to enums to reduce verbosity, it really helps when you have a method that take multiple enums.

i.e.

enum class LongEnumNameForSomeReason {
   foo, bar
}

enum class LongEnumNameForSomeOtherReason {
   foo, bar
}

fun multipleEnumParams(param1: LongEnumNameForSomeReason, param2: LongEnumNameForSomeOtherReason) = println("$param1\n$param2")

multipleEnumParams(LongEnumNameForSomeReason.foo, LongEnumNameForSomeOtherReason.bar)

// And to reduce verbosity we can have something like this (swift like)

multipleEnumParams(.foo, .bar)

The compiler knows for sure the enums for each param, so it will not be an issue to strip redundant code, in order to enhance readability of the code, also I found the case where having more than 2 enums your method need to be split in multiple lines, just because the names of the enums.

Regards

6 Likes

You can always use imports for that.

Not always, if you import several enums that way that have elements with the same name, they would conflict.

4 Likes

Ah, yes, I missed that. But it seems to be infinitely narrow use case.

2 Likes

Have you tried using shorter enum names?

But seriously, this just makes it harder for the reader to work out what the type of of an expression is, as if overloading and other features didn’t make it difficult enough.

1 Like

I don’t see an issue for the reader, because most of the time is the IDE that suggest the options, but in swift you could use both ways, starting with the enum class or just with a dot.

I tend to use nested enums just because, i.e.

class Person {
    enum class Gender { ... }
}

// instead of

enum class PersonGender { ... }

In both cases the length is almost the same, also having self explained class enums and enum cases helps you a lot to understand what it does. But heres an example, I’m building a wrapper around the opengl library of kotlin native (to be kotlin friendly) and it has a lot of method with a lot of parameter, and I thought it will be cool to have a shorter way to pass enum option as parameter. Also note that in this case the enums are not nested inside classes because opengl is oriented to functional programming.

1 Like

This.
And if there is conflict use import xyz as x

2 Likes

Completely forgot about it. Thanks.

and if the enum is defined in the same file (or not, and you just want to use this feature because), you can use a type alias. Between type aliases and named imports, I don’t think adding more sugar is necessary.

Maybe it is just the particular example in the OP, but in my opinion, despite the possible argument type inference, using ‘foo’ and ‘bar’ that exist in both enums makes it more confusing for a human reader when they are not qualified by their enum class or an alias for their enum class.

1 Like

Now I need an IDE to be able to read the code?