Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin equivalent of Swift string enum (typed set of string constants)

I have the following Swift enum:

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

Which allows me to have a typed set of constants and use them like:

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

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

What would be the equivalent of this in Kotlin?

like image 625
bbjay Avatar asked Jul 25 '18 19:07

bbjay


People also ask

What type is enum Kotlin?

Kotlin enums are classes, which means that they can have one or more constructors. Thus, you can initialize enum constants by passing the values required to one of the valid constructors. This is possible because enum constants are nothing other than instances of the enum class itself.

Can enum have functions Swift?

Cases as functions Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.

Should enum cases be capitalized Swift?

The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized.

What is enum Swift?

In Swift, an enum (short for enumeration) is a user-defined data type that has a fixed set of related values. We use the enum keyword to create an enum. For example, enum Season { case spring, summer, autumn, winter } Here, Season - name of the enum.


2 Answers

something like:

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

fun trackView(screenName : ScreenName) {
  print("viewed ${screenName.displayName}")
}
like image 103
Mateo Avatar answered Oct 11 '22 17:10

Mateo


Another possibility which I have discovered now, is with a sealed class:

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
        }
}

This has the advantage that it can mimic Swift enums with associated values.

like image 38
bbjay Avatar answered Oct 11 '22 19:10

bbjay