https://kotlinlang.org logo
Title
t

Tuang

02/18/2020, 3:20 AM
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

Leo

02/18/2020, 3:51 AM
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.
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

Barco

02/18/2020, 3:52 AM
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

Tuang

02/18/2020, 3:58 AM
@Barco i already tried
flatMap
, i cant retrieve name and country properties, i means
it.name, it.country
got error. here my sample 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

Barco

02/18/2020, 4:01 AM
You're defining your combineData as
Map<String, Any>,
change this to
mapOf<String, MyData>
and you'll be golden
t

Tuang

02/18/2020, 4:15 AM
@Barco yeah changing Any to MyData is golden, but in my case i need to become Any, that’s why 😪
b

Barco

02/18/2020, 4:18 AM
val valueOfData = combineData.values.flatMap { 
    if (it is MyData) listOf(it.name, it.country) else listOf() 
}
t

Tuang

02/18/2020, 4:19 AM
@Barco you are golden 😀 thx
1