Feature request: Implicit Import enum values

My idea is to allow assigning enum values without enum class prefix or explicit impor.

Here’s abstract usage example:

enum class ErrorPollicy {
   IGNORE,
   THROW_ERROR,
   WARNING
}

// Eg. variable assign
val errorPolicy:ErrorPollicy = IGNORE

// Eg. function call
fun handlerError(error: MyError, policy: ErrorPollicy) {
   TODO("...")
}
handleError(error, THROW_ERROR)

// Eg. jpa annotation usage
@OneToMany(cascade = [ALL])
lateinit var property: Property

I know it can be done with import of enum values, but it litters the rest of the file.
So the idea is to allow usage of enum names without importing it (of course if the type of statement is not ambiguous).

2 Likes

You can prepend to your own example with import ErrorPollicy.*, this should be enough.

‘Short notation for enum constants’ is in fact already being considered for a future version.

See item 3 in last year’s Future Features survey.

It was the 11th most popular (out of 20) and only a few folks were totally against it.

For cases where the compiler (and the human reader) is definitely expecting an enum value, it seems harmless enough to me and would be particularly useful in when statements which have an enum subject expression, so I’d be in favor.

1 Like

OMG, please don’t

companion object {
    val IGNORE = WARNING
}
val errorPolicy = IGNORE // Was it ErrorPolicy.IGNORE with "short notation" or property above?

Well, you can always abuse some feature or another to create terrible code :wink:
I personally like the idea of implicit enums in cases where the type is not ambiguous (eg. when statements). That being said I think this would be really bad

enum SomeEnum {
   A,
   B
}
val foo = A

because it would lead to a lot of ambiguity. What if someone adds another enum also containing A?
Again I would be fine with this

val foo: SomeEnum = A

As for your example, I think the compiler should show a warning in that case. Maybe even an error.

If I’ve understood the proposal correctly, then (thankfully) neither of those declarations would compile because the compiler would be unable to infer the type of the expression on the RHS.

However, this:

val errorPolicy: ErrorPolicy = IGNORE

would be fine as the enum type is clear to both the compiler and a human reader.

Or maybe like in swift?

val someVal: SomeEnum = .someValue

TBH I don’t really understand why Swift requires a leading dot.

If the compiler knows the type, then just specifying the enum value should be enough.

1 Like