xia*_*ian 2 enums kotlin kotlin-when
使用Swift 枚举,您可以省略名称enum,在只能使用该类型的值的情况下,。
所以当给出枚举(Swift/Kotlin)
enum (class) CompassPoint {
case north
case south
case east
case west
}
Run Code Online (Sandbox Code Playgroud)
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")
}
Run Code Online (Sandbox Code Playgroud)
在 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")
}
Run Code Online (Sandbox Code Playgroud)
是否有原因,和/或在 Kotlin 中是否存在可以使用.north或north可以使用的情况?
编辑:似乎导入枚举“修复”了这一点,即使枚举在使用时在同一文件中定义也是必要的。
虽然这实际上有帮助,但我仍然不明白为什么需要导入。