zain
07/26/2022, 11:49 AMdata 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?ephemient
07/26/2022, 12:02 PMfor (property in Stat::class.declaredMemberProperties) {
println("${property.name}=${property.get(stat)}")
}
zain
07/26/2022, 12:08 PMJoffrey
07/26/2022, 12:27 PMzain
07/26/2022, 12:30 PMephemient
07/26/2022, 12:36 PMkotlin-reflect
artifact for my code snippet. but if this is a repeating problem then I would generate a static list with #ksp or similar
val statProps = listOf(
Stat::bR,
Stat::cS,
...
to avoid the overheadErick Sumargo
07/26/2022, 12:51 PM{
"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.gabfssilva
07/26/2022, 1:22 PMfun 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) -> ... }
denis
07/26/2022, 1:25 PMStephan Schroeder
07/27/2022, 8:41 AMfun Stat.asMap() = mapOf<String, Int?> (
"bR" to bR,
"cS" to cS,
...
)