Im often in the situation that I have an enum clas...
# announcements
p
Im often in the situation that I have an enum class and that I want to have a value for each enum member. For example
enum class BaseNutrient
->
Map<BaseNutrient, Double>
. Is there a more elegant way than using
Basenutrient.values().associate { baseNutrient -> baseNutrient to 0.0 }
As I need that so frequently it feels like I’m overseeing sth in the stdlib
p
There is
associateWith
function where you need to return just a value instead of a pair. So you can write
list.associateWith { 0.0 }
. But this function is defined for
Iterable
only. So I usually define my own extension function:
Copy code
inline fun <K, V> Array<out K>.associateWith(valueSelector: (K) -> V): Map<K, V> {
    return asIterable().associateWith(valueSelector)
}
a
Why not just declare it properly?
Copy code
enum class BaseNutrient(val value:Double){
    NOODLE(100.0),
    CARROT(50.0),
  }
👍 2
p
In my use-case this value is calculated. Something like this:
Copy code
MyEnum.values().associateWith { foo(it) }
But if it is constant, then yes, property is the way to go.
p
Ok I’ll open a ticket for this, thanks
👍 1
d
@Pavlo Liapota Is it calculated statically or dynamically? Either way, wouldn't an option be to just ascribe a function to each Enum, like:
Copy code
enum class Nutrient(val value:(Nutrient)->Double){
    APPLE(myNutrientFunctionFruit),
    CARROT(myNutrientFunctionVeg),
    SWEDE(myNutrientFunctionVeg);

    val kiloJoules : Double get() = this.value()
  }