Omitting enum name possible when it is imported?

I just created a post on Stackoverflow asking about why I can’t omit the enum name when it’s type is clear, like here:

    // type unclear, enum name needed
var directionToHead = CompassPoint.west

// type clear, enum name still needed
directionToHead = CompassPoint.east

// each case needs the enum name
when(directionToHead) {
  CompassPoint.north -> println("Lots of planets have a north")
  CompassPoint.south -> println("Watch out for penguins")
  CompassPoint.east -> println("Where the sun rises")
  CompassPoint.west -> println("Where the skies are blue")

The suggested solution is to import CompassPoint.* which I tried and what strangely helped here.
I have the enum defined in the same file as the when, so I don’t understand why importing it helps here.

Why isn’t it allowed to omit the enum name, when the type is clear?

The names that you can use without qualification are not related to the types of variables at all.

They are only affected by the type of this (you can access members) and imports. And of course local variables/parameters work too.

As well as package functions/properties within the same package.

Java supports omitting the enum class name for cases in a switch statement, although that’s because Java only allows a few specific types to be switched on, so it has particular support for when that type is an enum. It would be nice for this to be available in Kotlin as well (and for sealed classes), though it would be a bit more difficult.

1 Like

Ah, this was one of the features in the feature survey back in 2017:

Number 3 to be exact


Thanks! This helps to understand the reason behind this a little better.

Thats what I thought.

The 2017 survey linked by @tieskedh shows that there are a lot other developers thinking the same. While i now know about the possibility to import CompassPoint.* that would still be something very different. Especially in cases where there are multiple enums that might have overlapping states using the enum import would make it worse… I think’ll be keeping the full name for now.

Thanks for linking! Interesting survey… I just started using Kotlin this year. Seems there are others wishing for the same feature. You can even see the third point on one of their photos and see that it has a lot of stickers on it :slight_smile:
Maybe it will be added later…

To be entirely correct, in 2017 there were a lot of developers who liked it.
Now Kotlin is more stabale, the visions could be changed.
(Don’t know why this one would be changed, though)