dave08
10/10/2018, 12:56 PMList
of a few different enums with a common property val
? I'd need to be able to retreive the list of entries and get the value of that property for each...miha-x64
10/10/2018, 1:06 PMdave08
10/10/2018, 1:21 PMinterface RestrictionKey {
val key: String
}
enum VRestrictions(name: String): RestrictionKey {
ONE("one"), TWO("two");
override val key = "pr.$name"
}
enum YRestrictions(name: String): RestrictionKey {
THREE("three"), FOUR("four");
override val key = "pr.$name"
}
val restrictionTypes = listOf(VRestrictions, YRestrictions).flatMap { it.entries.map { it.key } }
I need something like that, but how would I get the entries...?David W
10/10/2018, 1:23 PM(it as RestrictionKey).key
?dave08
10/10/2018, 1:25 PMentries
property that I can't access...David W
10/10/2018, 1:28 PMval restrictionTypes = (VRestrictions.values() + YRestrictions.values()).map { (it as RestrictionKey).key } }
Dico
10/10/2018, 1:29 PMval values = arrayOf<RestrictionKey>(*enumValues<VRestrictions>(), *enumValues<YRestrictions>())
David W
10/10/2018, 1:29 PMDico
10/10/2018, 1:30 PMDavid W
10/10/2018, 1:32 PMval restrictionTypes = (VRestrictions.values().toList() + YRestrictions.values()).map { (it as RestrictionKey).key } }
miha-x64
10/10/2018, 1:34 PMYou can't just concatenate the arraysAFAIK, you can do both.
Dico
10/10/2018, 1:34 PMDavid W
10/10/2018, 1:34 PMDico
10/10/2018, 1:35 PMmiha-x64
10/10/2018, 1:37 PMenumValues<T>
is reflective, T.values()
is not.Dico
10/10/2018, 1:38 PMdave08
10/10/2018, 1:39 PMRestrictionsStore
to validate all the possible keys coming in from an API before being saved... so maybe not necessary to pass the actual enums in that case.
Reflective meaning using reflection to get the values?Dico
10/10/2018, 1:40 PMenumValues<T>
exists to be able to get the values()
of a reified
type parameter. It is inlined by the compiler and produces exactly the same call.miha-x64
10/10/2018, 1:41 PMwhat makes it reflective?My bad it's not. I thought it uses Java's
getEnumConstants()
, but it doesn't.Dico
10/10/2018, 1:46 PMinterface RestrictionKey
object RestrictionKeys {
private val values = mutableListOf<RestrictionKey>()
val allKeys: List<RestrictionKey> get() = values
fun register(vararg keys: RestrictionKey) {
// filter logic here
values += keys
}
inline fun <reified T> register()
where T : Enum<T>, T : RestrictionKey {
register(*enumValues<T>())
}
}
fun main() {
RestrictionKeys.register<YRestrictions>()
RestrictionKeys.register<VRestrictions>()
for (key in RestrictionKeys.allKeys) {
// use keys?
}
}
David W
10/10/2018, 1:47 PMdave08
10/10/2018, 1:50 PMmiha-x64
10/10/2018, 1:50 PM+
operator: https://kotlinlang.slack.com/archives/C0B8Q383C/p1539179399000100David W
10/10/2018, 1:51 PMA.values().toList() + B.values()
Dico
10/10/2018, 1:56 PMmiha-x64
10/10/2018, 1:57 PMObject[]
array type everywhereDico
10/10/2018, 1:58 PM