Hello. I have an `object` with constants defined a...
# getting-started
v
Hello. I have an
object
with constants defined as
const val
. I want to get a list of all constants available in this object. Is there a convenient way to get them? I tried with reflection:
MyObjectWithConstant::class.declaredMemberProperties
j
You could define your constants using a property delegate that registers them in a list or map. Something like this: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1632152724002800?thread_ts=1632151317.001400&cid=C0B8MA7FA
e
can't have delegates with
const val
, so if that's important to you, you'll need to use other approaches like reflection or codegen
šŸ‘ 1
v
Thanks! What is ā€œPeter approachesā€?
j
Might be an auto-corrected "other" šŸ˜„
v
Donā€™t think that
const val
is so important
Thanks @Joffrey! I think your proposed solution will work for me!
e
autocorrect whyyyyy
anyhow, reflection isn't too hard:
Copy code
MyObjectWithConstant::class.declaredMemberProperties.filter { it.isConst }.associate { it.name to it.call() }
but does have a downside of being limited to JVM only
šŸ‘ 1
the delegate trick is interesting, you might want to make it
private
so nobody else can mess with it. I'd probably choose to do something with kapt/ksp to generate a table of constants at compile-time if I had to (it would work with
const
too)