How to convert a Kotlin data class object to map?

前端 未结 6 1539
一个人的身影
一个人的身影 2020-12-09 02:39

Is there any easy way or any standard library method to convert a Kotlin data class object to a map/dictionary of it\'s properties by property names? Can reflection be avoid

6条回答
  •  借酒劲吻你
    2020-12-09 03:36

    This extension function uses reflection, but maybe it'll help someone like me coming across this in the future:

    inline fun  T.asMap() : Map {
        val props = T::class.memberProperties.associateBy { it.name }
        return props.keys.associateWith { props[it]?.get(this) }
    }
    

提交回复
热议问题