Search code examples
androidandroid-studiokotlinreflectiondata-class

Error getting the values of all fields of a data class


I am trying to get all the field values of a data class using this extension function:

fun FinancialDataResponse.asDomainModel() = FinancialData(
    heading = this::class.memberProperties.map { it.name },
    data = this::class.memberProperties.map {it.get(this).toString()}
)

But I keep getting this error :

Can someone please tell me what will be the right way to get the values of all the fields for a data class in kotlin?

Any kind of help will be appreciated. Thanks in advance !


Solution

  • You want the getter.call method instead. This will work:

    fun FinancialDataResponse.asDomainModel() = FinancialData(
    heading = this::class.memberProperties.map { it.name },
    data = this::class.memberProperties.map { it.getter.call(this).toString() })