Enums with Properties and Functions

Constructor Properties

Enums can have a constructor, properties and functions. Each constant passes its own values. When you add members, end the constant list with a semicolon.

Example

enum class Plan(val label: String, val monthlyPrice: Int, val screens: Int) {
    MOBILE("Mobile", 149, 1),
    BASIC("Basic", 199, 1),
    STANDARD("Standard", 499, 2),
    PREMIUM("Premium", 649, 4);

    fun yearlyPrice() = monthlyPrice * 12
    fun isFamilyPlan() = screens >= 4
}

fun main() {
    for (plan in Plan.entries) {
        println("%-8s Rs %3d/month  Rs %4d/year  family=%s".format(
            plan.label, plan.monthlyPrice, plan.yearlyPrice(), plan.isFamilyPlan()))
    }
}

Output

Mobile   Rs 149/month  Rs 1788/year  family=false
Basic    Rs 199/month  Rs 2388/year  family=false
Standard Rs 499/month  Rs 5988/year  family=false
Premium  Rs 649/month  Rs 7788/year  family=true

Companion Lookup

Example

A companion object (covered later) is a handy place for a "find by code" function - useful when the server sends codes instead of names.

enum class Language(val code: String) {
    ENGLISH("en"), HINDI("hi"), TELUGU("te"), TAMIL("ta");

    companion object {
        fun fromCode(code: String) = entries.find { it.code == code } ?: ENGLISH
    }
}

fun main() {
    println(Language.fromCode("te"))
    println(Language.fromCode("fr"))   // falls back to ENGLISH
}

Output

TELUGU
ENGLISH