简体   繁体   中英

How to sort objects by dynamical fields kotlin

I am wondering how to make sorting by dynamic field using kotlin. Let's sat I have the following:

class Example(
  val prop1: String,
  val prop2: String,
  val prop3: Int,
  ....
  ....
  val prop100: String
)

fun sort(sortProperty: String, sortDirection: String) {
  return listOf(Example(), Example()).sortWith(compareBy(sortProperty, sortDirection))
}

How I can make a sorting by any field of Example class?

I was able to resolve that like this

class MyComparator(
   private val sortProperty: String? = null,
   private val isAscending: Boolean
): Comparator<Data> {

override fun compare(o1: Data?, o2: Data?): Int {
    val kProperty1 = Data::class.declaredMemberProperties.firstOrNull { it.name == sortProperty }
    return if (kProperty1 != null) {
        val valueFirst = kProperty1.get(o1!!).toString()
        val valueSecond = kProperty1.get(o2!!).toString()
        if (isAscending) valueFirst.compareTo(valueSecond) else valueSecond.compareTo(valueFirst)
    } else {
        val idProperty = Data::id
        val valueFirst = idProperty.get(o1!!)
        val valueSecond = idProperty.get(o2!!)
        if (isAscending) valueFirst.compareTo(valueSecond) else valueSecond.compareTo(valueFirst)
    }
}

}

From the code:

totalResults.sortedWith(comparator = MyComparator(sortProperty, isAscending))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM