Enums in Kotlin are very similar to those in Java. In the following we've defined a basic enum class named ArticleType:
enum class ArticleType {
Aside,
Blog,
Series
}
This then can be used as a restricted type anywhere we would use any other existing type. In the following snippet, we've defined a property on Article using the new ArticleType enum:
data class Article(
var title: String,
val author: String,
val type: ArticleType
)
When instantiating an instance of Article, we can reference the specific values exposed in our ArticleType enum:
fun main(args: Array<String>) {
val article1 = Article(
"Kotlin is great",
"Nate",
ArticleType.Blog
)
}
By limiting the article types to those defined within ArticleType, we've provided a clear contract to users of the Article class, and it clearly defines what types the developer must account for.
We can add properties to our enum values, as seen in this example:
enum class ArticleType(val displayName: String) {
Aside("Small Post"),
Blog("Standard Blog Post"),
Series("Part of a Blog Series")
}
We can then access those enum properties like any other property:
fun main(args: Array<String>) {
println(ArticleType.Blog.displayName)
}
Enums can be a great way of enforcing a limited set of type options for some value when those types don't require any additional data or state of their own. For cases where we want a restricted set of types, but those types require their own data, we can turn to sealed classes.