Swift-like enum selection

My problem is short, insignificant but quality of life.

In Swift, if you declare an enum, let’s say

enum Directions {
  case north
  case south
}

And you declare a function as follows

func doSomething(_ direction: Directions) { ... }

Then you can call the function like this, without specifying the enum type:

doSomething(.north)
// compared to
doSomething(Directions.north)

Can this be implemented in Kotlin too?

4 Likes

This has already been discussed in some threads:

I really don’t understand the cons that people bring up.

When it comes to readability, enums are usually self explanatory, and sometimes the enum name is just additional clutter.

Here’s an example:

enum class LineClearMethod(val raw: Int) {
    FromCursorToEnd(0),
    FromCursorToBeginning(1),
    WholeLine(2)
}
fun clearLine(method: LineClearMethod = LineClearMethod.WholeLine) : String {
    return CSI[method.raw.toString() + "K"]
}

Calling clearLine looks like this:

clearLine(LineClearMethod.FromCursorToEnd)

I would argue that the following case is self explanatory, as easy (if not easier) to understand and it’s the case found most often when using enums:

clearLine(.FromCursorToEnd)

Also, the workarounds proposed are very impractical.
Renaming the enum with an import defeats the whole readability argument and importing everything clutters the context and causes potential for name clashing (think of enums containing color names).

When the compiler clearly knows the type of enum expected, not having to specify it and just using the .ENUM_VALUE syntax seems like a “why wasn’t this a thing in the first place?” kind of thing.

5 Likes

It’s definitely time for an issue on youtrack about this

Please vote