Skip to content

Instantly share code, notes, and snippets.

@mskoroglu
Last active July 6, 2022 09:34
Show Gist options
  • Save mskoroglu/41fbd88e719d2302a1a22ce30862823c to your computer and use it in GitHub Desktop.
Save mskoroglu/41fbd88e719d2302a1a22ce30862823c to your computer and use it in GitHub Desktop.
Kotlin extension functions for sorting by locale(lang, country)
// Example: cities.sortedWithLocaleBy(Locale("tr")) { it.name }
inline fun <T, R : Comparable<R>> Iterable<T>.sortedWithLocaleBy(
locale: java.util.Locale,
crossinline selector: (T) -> R?
) = sortedWith(compareBy(java.text.Collator.getInstance(locale), selector))
// Example: cities.sortedWithLocaleByDescending(Locale("tr")) { it.name }
inline fun <T, R : Comparable<R>> Iterable<T>.sortedWithLocaleByDescending(
locale: java.util.Locale,
crossinline selector: (T) -> R?
) = sortedWith(compareByDescending(java.text.Collator.getInstance(locale), selector))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment