Using condition to select the sorting property in Kotlin -


i using sortedby() perform sorting on collection of objects.

since order may change depending on user choice, i've ended following code

val sortedlist = if (sortingorder == wordsortingorder.by_alpha) {                     list.sortedby { it.word.value }                 } else {                     list.sortedby { it.createdat }                 } 

then perform further actions on sorted collection. realize sortedby() method expects property returned. wonder if there way embed sorting condition in 1 chain of collection methods.

if properties of different types won't able select 1 of them based on condition result sortedby, common supertype inferred any , not subtype of comparable<r> sortedby expects.

instead can utilize sortedwith method, takes comparator, , provide comparator depending on condition:

list.sortedwith(     if (sortingorder == wordsortingorder.by_alpha)         compareby { it.word.value }     else         compareby { it.createdat } ) 

comparators different properties created here kotlin.comparisons.compareby function.

you can extract logic selects comparator based on sorting order function:

list.sortedwith(comparatorfor(sortingorder))  fun comparatorfor(sortingorder: wordsortingorder): comparator<mytype> = ... 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -