In the following data, [MyData(name=mike, country=...
# getting-started
t
In the following data, [MyData(name=mike, country=mm), MyData(name=tike, country=bkk)] how to retrieves all member of MyData and transform as one list? what i want to do is, [“mike”, “mm”, “tike”, “bkk”]
l
I would use reflection in a loop, but there is probably a better way Data classes have methods called component1(), component2()…. componentN(), which follow declaration order So you could do something this to get the fields for one single instance. If you want to add fields from many instances to your list, you can add a second for loop, or a forEach, etc, to loop through a collection of instances.
Copy code
fun MyData.toList(): List<Any> {
    val result = ArrayList<Any>()
    
    for (i in 1..Int.MAX_VALUE) {
        try {
            val getter = javaClass.getMethod("component$i")
            val item = getter.invoke(this)!!
            result.add(item)
        } catch (e: Exception) {
            break
        }
    }
    return result
}
b
myDataList.flatMap { listOf(it.name, it.country) }
This will map each of your
MyData
instances into a list and then flatten out those lists.
👍 1
t
@Barco i already tried
flatMap
, i cant retrieve name and country properties, i means
it.name, it.country
got error. here my sample code
Copy code
fun main() {
    val data1 = MyData("mike", "mm")
    val data2 = MyData("tike", "bkk")
    val combineData = mapOf<String, Any>("Data1" to data1, "Data2" to data2)
    val valueOfData = combineData.values

}

data class MyData(val name: String, val country: String)

enum class TestEnum(val str: List<String>) {
    TEST1(listOf("a", "b", "c")),
    TEST2(listOf("d", "e", "f"));
}
b
You're defining your combineData as
Map<String, Any>,
change this to
mapOf<String, MyData>
and you'll be golden
t
@Barco yeah changing Any to MyData is golden, but in my case i need to become Any, that’s why 😪
b
Copy code
val valueOfData = combineData.values.flatMap { 
    if (it is MyData) listOf(it.name, it.country) else listOf() 
}
t
@Barco you are golden 😀 thx
1