When we have a fixed set of predefined constants, it is considered a good practice grouping them in an enum
type.
Sample Usage
1. Simple Enum
[wp_ad_camp_1]
1 2 3 4 5 6 7 8 9 10 11 | package exercise01.enumtest /** * Created by Turreta.com on 19/6/2017. */ enum class ProductStatus { NEW, SHIPPED, PACKED, WITH_DEFECT } |
Sample usage:
1 2 3 4 5 | fun main(args: Array<String>) { println(ProductStatus.NEW) println(ProductStatus.WITH_DEFECT) println(ProductStatus.PACKED == ProductStatus.valueOf("PACKED")) } |
Outputs:
1 2 3 | NEW WITH_DEFECT true |
2. Enum with Instance Method and Field
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package exercise01.enumtest /** * Created by Turreta.com on 19/6/2017. */ enum class Seasons(val seasonName: String) { WINTER("winter"), SPRING("spring"), SUMMER("summer"), FALL("fall"); fun toUpper() : String { return seasonName.toUpperCase() } } |
Sample usage:
1 2 3 4 5 6 7 | package exercise01.enumtest fun main(args: Array<String>) { println(Seasons.FALL) println(Seasons.SPRING.toUpper()) println(Seasons.WINTER.ordinal) } |
Outputs:
1 2 3 | FALL SPRING 0 |
3. List all Enum types
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 | package exercise01.enumtest fun main(args: Array<String>) { Seasons.values().forEach { println(it) } } |
Outputs:
1 2 3 4 | WINTER SPRING SUMMER FALL |
References
https://kotlinlang.org/docs/reference/enum-classes.html
[wp_ad_camp_4]