Kotlin相当于Swift字符串枚举(字符串常量的类型化集合)

时间:2018-07-25 19:19:13

标签: swift enums kotlin

我有以下Swift枚举:

enum ScreenName: String {
    case start = "Start Screen"
    case dashboard = "My Dashboard Screen"
}

这允许我拥有一组类型化的常量,并像这样使用它们:

func trackView(screen: ScreenName) {
     print("viewed \(screen.rawValue)")
}

trackView(screen: .start) // -> "viewed Start Screen"

在Kotlin中这相当于什么?

2 个答案:

答案 0 :(得分:4)

类似:

enum class ScreenName(val displayName : String) { 
  START("Start Screen"), 
  DASHBOARD("My Dashboard Screen") 
}

fun trackView(screenName : ScreenName) {
  print("viewed ${screenName.displayName}")
}

答案 1 :(得分:2)

我现在发现的另一种可能性是使用密封类:

sealed class ScreenName(val name : String) {
    object Start :     ScreenName("Start Screen")
    object Dashboard : ScreenName("My Dashboard Screen")

    data class NewsDetail(val title: String) : ScreenName("News")

    val displayName: String
        get() = when(this) {
            is NewsDetail -> "${name} - ${title}"
            else -> name
        }
}

它的优点是可以模仿带有关联值的Swift枚举。