https://kotlinlang.org logo
#announcements
Title
# announcements
p

Paul Woitaschek

08/27/2019, 6:56 AM
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

Pavlo Liapota

08/27/2019, 7:11 AM
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

Amirul Zin

08/27/2019, 7:12 AM
Why not just declare it properly?
Copy code
enum class BaseNutrient(val value:Double){
    NOODLE(100.0),
    CARROT(50.0),
  }
👍 2
p

Pavlo Liapota

08/27/2019, 7:16 AM
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

Paul Woitaschek

08/27/2019, 7:18 AM
Ok I’ll open a ticket for this, thanks
👍 1
d

darkmoon_uk

08/28/2019, 7:09 AM
@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()
  }
2 Views