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

zain

07/26/2022, 11:49 AM
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

ephemient

07/26/2022, 12:02 PM
with reflection, it is possible
Copy code
for (property in Stat::class.declaredMemberProperties) {
    println("${property.name}=${property.get(stat)}")
}
z

zain

07/26/2022, 12:08 PM
@ephemient Do I need to add a dependency I use kotlin 1.6
j

Joffrey

07/26/2022, 12:27 PM
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

zain

07/26/2022, 12:30 PM
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

ephemient

07/26/2022, 12:36 PM
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

Erick Sumargo

07/26/2022, 12:51 PM
@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

gabfssilva

07/26/2022, 1:22 PM
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

Stephan Schroeder

07/27/2022, 8:41 AM
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,
  ...
)
3 Views