Kotlin:明确时省略枚举名称

Kotlin: Omitting enum name when its unambiguous

使用 Swift enums,在只能使用该类型的值的情况下,您可以省略 enum 的名称。

所以当给出枚举时 (Swift/Kotlin)

enum (class) CompassPoint {
  case north
  case south
  case east
  case west
}

Swift 创建新变量时只需要枚举名称:

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

// type clear, enum name can be dropped
directionToHead = .east

// type clear, enum name can be dropped
switch directionToHead {
case .north:
  print("Lots of planets have a north")
case .south:
  print("Watch out for penguins")
case .east:
  print("Where the sun rises")
case .west:
  print("Where the skies are blue")
}

在 Kotlin 中,对于相同的情况,您必须编写

// 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")
}

这有什么原因吗,and/or Kotlin 中是否存在只能使用 .northnorth 的情况?

Edit: It seems importing the enum 'fixes' this and is necessary even when the enum is defined in the same file as it is used.

虽然这实际上有所帮助,但我仍然不明白为什么需要导入。

只需使用 import,这样您就可以使用没有枚举名称的枚举值

  import CompassPoint.*

Edit: It seems importing the enum 'fixes' this and is necessary even when the enum is defined in the same file as it is used.

While this helped practically, I still don't understand why the import is needed.

只是因为没有特殊对待。 import CompassPoint.* 让你只写 <name> 任何你想写成 CompassPoint.<name> 没有它的东西(如果名字不与任何东西冲突)。如果你碰巧在定义CompassName的文件中,它的工作原理完全一样。

您可以将值引用为 north 等,而无需在枚举定义中导入 ,就像您可以引用 object 一样此对象内的成员:

object Obj {
    val v = 0
    val v1 = v
}

val v2 = Obj.v

import Obj.* // or import Obj.v
val v2 = v

FWIW,Kotlin 团队正在考虑在枚举类型明确时实现非限定枚举常量。

他们目前正在进行一项功能调查以收集反馈,unqualified enum constants 也在其中。