arturro
07/10/2017, 12:09 PMif (v1 == null && v2 == null) {
return 0
}
if (v1 != null && v2 == null) {
return 1
}
if (v1 == null && v2 != null) {
return -1
}
diesieben07
07/10/2017, 12:11 PMarturro
07/10/2017, 12:15 PMoverride fun compare(o1: T, o2: T): Int {
val property = o1.javaClass.kotlin.declaredMemberProperties.first { it -> it.name == propertyName }
val v1 = property.get(o1) as? Comparable<Any>
val v2 = property.get(o2) as? Comparable<Any>
if (v1 == null && v2 == null) {
return 0
}
if (v1 != null && v2 == null) {
return 1
}
if (v1 == null && v2 != null) {
return -1
}
return v1!!.compareTo(v2!!)
}
diesieben07
07/10/2017, 12:17 PMval c = compareBy(MyClass::property)
arturro
07/10/2017, 12:18 PMdiesieben07
07/10/2017, 12:18 PMcompareBy
.nullsLast
resp. nullsFirst
to allow nulls.arturro
07/10/2017, 12:28 PMfun <T : Any> List<T>.sortByProperty(propertyName: String, asc: Boolean = true) : List<T> {
val field = ???
return this.sortedBy { field }
}
But it does'n compile.diesieben07
07/10/2017, 12:36 PMT
would have to be reified so you can get it's class. Then you can use T::class to look up the propertypropertyName
should really not be a string though..cedric
07/10/2017, 12:48 PMarturro
07/10/2017, 12:50 PMcedric
07/10/2017, 12:51 PMcompare
arturro
07/10/2017, 12:51 PMinline fun <reified T : Any> List<T>.sortByPropertyName(propertyName: String) : List<T> {
val prop = T::class.declaredMemberProperties.first { it.name == propertyName }
return this.sortedBy { prop }
}
But it doesn't compile, the error is:
Error:(11, 17) Kotlin: Type parameter bound for R in inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T>
is not satisfied: inferred type KProperty1<T, *> is not a subtype of Comparable<KProperty1<T, *>>
cedric
07/10/2017, 2:07 PMprop
itself does not implement Comparable
, you need code in there that can be mapped by the compiler to a Comparable
return this.sortedBy { -1 }
(obviously not what you want but you get the idea)artur
07/10/2017, 2:19 PM