标准二进制麦克斯比功能



我概括了以下代码:

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参考

实现这一目标的最简单方法,因为Kotlin 1.1是Maxof方法。

最新更新