https://kotlinlang.org logo
#getting-started
Title
# getting-started
v

Vitali Plagov

09/28/2021, 10:15 AM
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

Joffrey

09/28/2021, 10:17 AM
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

ephemient

09/28/2021, 10:27 AM
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

Vitali Plagov

09/28/2021, 10:29 AM
Thanks! What is “Peter approaches”?
j

Joffrey

09/28/2021, 10:30 AM
Might be an auto-corrected "other" 😄
v

Vitali Plagov

09/28/2021, 10:31 AM
Don’t think that
const val
is so important
Thanks @Joffrey! I think your proposed solution will work for me!
e

ephemient

09/28/2021, 3:52 PM
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)
2 Views