I have this data class in Stat, all properties hav...
# getting-started
z
I have this data class in Stat, all properties have some default value.
Copy code
data class Stat(
    val bR: Int?  = 1,
    val cS: Int? = 2,
    val fP: Int? = 3,
    val gA: Int? = 4,
    val gC: Int? = 5,
    val gOB: Int? = 6,
    val gS: Int? = 7
)
How do I get all properties and their respective values of an object? val stat = Stat( ) stat.forEach { property, value } Is this possible in Kotlin?
e
with reflection, it is possible
Copy code
for (property in Stat::class.declaredMemberProperties) {
    println("${property.name}=${property.get(stat)}")
}
z
@ephemient Do I need to add a dependency I use kotlin 1.6
j
While reflection is possible, it is usually not intended for business-oriented use cases. If you need to do this, you might want to design the class differently instead. For instance, using a map might be more appropriate depending on how you intend to use it
👍 3
z
The problem is that the backend team designed it away, and the use case is to show it as a list. It is so tightly coupled that I have to develop this smartly
e
you need the
kotlin-reflect
artifact for my code snippet. but if this is a repeating problem then I would generate a static list with #ksp or similar
Copy code
val statProps = listOf(
    Stat::bR,
    Stat::cS,
    ...
to avoid the overhead
1
e
@zain what's the sample of the backend response? I guess something like this?
Copy code
{
  "bR": 1,
  "cS": 2,
  ...
}
if yes, then you can follow what @Joffrey suggested. Turn your Retrofit body object into Map<String, Int> and you're good to go.
g
I agree with @Joffrey & @Erick Sumargo, it would be better (faster & simpler) to use map in this case:
Copy code
fun stat(
  val bR: Int? = 1,
  val cS: Int? = 2,
  ...
) = mapOf(
  "bR" to bR,
  "cS" to cS,
  ...
)

val stat = stat() //you can override the default properties just like in a data class

//and now you can get the name of each property alongside its value
stat.forEach { (key, value) -> ... }
d
s
you could write an extension function to get a map representation:
Copy code
fun Stat.asMap() = mapOf<String, Int?> (
  "bR" to bR,
  "cS" to cS,
  ...
)