compareValuesBy

fun <T> compareValuesBy(
    a: T,
    b: T,
    vararg selectors: (T) -> Comparable<*>?
): Int
(source)

Compares two values using the specified functions selectors to calculate the result of the comparison. The functions are called sequentially, receive the given values a and b and return Comparable objects. As soon as the Comparable instances returned by a function for a and b values do not compare as equal, the result of that comparison is returned.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
fun compareLengthThenString(a: String, b: String): Int =
    compareValuesBy(a, b, { it.length }, { it })

println("compareLengthThenString("b", "aa") < 0 is ${compareLengthThenString("b", "aa") < 0}") // true

println("compareLengthThenString("a", "b") < 0 is ${compareLengthThenString("a", "b") < 0}") // true
println("compareLengthThenString("b", "a") > 0 is ${compareLengthThenString("b", "a") > 0}") // true
println("compareLengthThenString("a", "a") == 0 is ${compareLengthThenString("a", "a") == 0}") // true
//sampleEnd
}
inline fun <T> compareValuesBy(
    a: T,
    b: T,
    selector: (T) -> Comparable<*>?
): Int
(source)

Compares two values using the specified selector function to calculate the result of the comparison. The function is applied to the given values a and b and return Comparable objects. The result of comparison of these Comparable instances is returned.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
fun compareLength(a: String, b: String): Int =
    compareValuesBy(a, b) { it.length }

println("compareLength("a", "b") == 0 is ${compareLength("a", "b") == 0}") // true
println("compareLength("bb", "a") > 0 is ${compareLength("bb", "a") > 0}") // true
println("compareLength("a", "bb") < 0 is ${compareLength("a", "bb") < 0}") // true
//sampleEnd
}
inline fun <T, K> compareValuesBy(
    a: T,
    b: T,
    comparator: Comparator<in K>,
    selector: (T) -> K
): Int
(source)

Compares two values using the specified selector function to calculate the result of the comparison. The function is applied to the given values a and b and return objects of type K which are then being compared with the given comparator.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
fun compareInsensitiveOrder(a: Char, b: Char): Int =
    compareValuesBy(a, b, String.CASE_INSENSITIVE_ORDER, { c -> c.toString() })

println("compareInsensitiveOrder('a', 'a') == 0 is ${compareInsensitiveOrder('a', 'a') == 0}") // true
println("compareInsensitiveOrder('a', 'A') == 0 is ${compareInsensitiveOrder('a', 'A') == 0}") // true

println("compareInsensitiveOrder('a', 'b') < 0 is ${compareInsensitiveOrder('a', 'b') < 0}") // true
println("compareInsensitiveOrder('A', 'b') < 0 is ${compareInsensitiveOrder('A', 'b') < 0}") // true
println("compareInsensitiveOrder('b', 'a') > 0 is ${compareInsensitiveOrder('b', 'a') > 0}") // true
//sampleEnd
}