【发布时间】:2020-06-12 22:48:30
【问题描述】:
对于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")
}
这是否有原因,和/或在 Kotlin 中是否存在只能使用 .north 或 north 的情况?
编辑:似乎导入枚举“修复”了这个问题,即使枚举定义在与它使用的文件相同的文件中也是必要的。
虽然这实际上有所帮助,但我仍然不明白为什么需要导入。
【问题讨论】:
-
如果添加枚举的静态导入,枚举类名可以省略。
标签: kotlin enums kotlin-when