Saturday, 21 April 2018

Kotlin - Static Method at Enum

Enum allows you to create a singleton with all distinct values and the method "valueOf" allow you to loop through all the existing values, which makes it unique and values.

On Kotlin, it is used by creating Companion Objects on the enum class, like the following one:

enum class Currency (val code: String, val exchangeRate: Float){
    //Average from: http://www.x-rates.com/average/?from=RUB&to=AED&amount=1&year=2016
    DIRHAMS("AED", 1.00f), // United Arab Emirates
    DOLLAR("USD", 3.67f), // US dollar
    EURO("EUR", 4.10f), // Euro
    UNKNOWN("Unknown", 1.00f); // The rate for unknown currency is 1:1
    companion object {
        fun toCurrency(code: String): Currency {
            if(TextUtils.isEmpty(code)) {
                return UNKNOWN
            }
            for (currency: Currency in values()) {
                if (currency.code == code) {
                    return currency
                }
            }
            return UNKNOWN
        }
    }
}

Now, the access to it is a bit different. The keyword "Companion" must be written between the class and the class method:

Currency.Companion.toCurrency("AED");

Reference:

No comments:

Post a Comment