标准的二进制maxBy函数

我概括了下面的代码:

fun max(that: Type): Type = if (this.rank() < that.rank()) that else this 

对此:

 fun max(that: Type): Type = maxBy(this, that) { it.rank() } fun maxBy<T, U : Comparable<U>>(a: T, b: T, f: (T) -> U): T = if (f(a) < f(b)) b else a 

在Kotlin的标准库中是否有像maxBy这样的函数? 我只能找到一个数组。

Kotlin stdlib 在Iterable上有maxmaxBy 扩展函数

max的签名是:

 fun <T : Comparable<T>> Iterable<T>.max(): T? 

maxBy的签名是:

 fun <T, R : Comparable<R>> Iterable<T>.maxBy( selector: (T) -> R ): T? 

要么与可比价值工作。 maxBy使用lambda来创建与每个项目相当的值。

这里是一个测试案例,展示了两个行动:

 @Test fun testSO30034197() { // max: val data = listOf(1, 5, 3, 9, 4) assertEquals(9, data.max()) // maxBy: data class Person(val name: String, val age: Int) val people = listOf(Person("Felipe", 25), Person("Santiago", 10), Person("Davíd", 33)) assertEquals(Person("Davíd", 33), people.maxBy { it.age }) } 

另请参阅: Kotlin API参考