首页 > 解决方案 > 成员参考不适用于 Kotlin 不可变列表中的 maxBy

问题描述

这是我的代码不起作用:

    val people = listOf(Person("Tarun", 28), Person("Shyam", 25), Person("Pushpraj", 27))
    people.maxBy { Person::age }

上述代码出现的错误:

Type parameter bound for R in inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? is not satisfied: inferred type KProperty1<Person, Int> is not a subtype of Comparable<KProperty1<Person, Int>>

工作代码:

    val people = listOf(Person("Tarun", 28), Person("Shyam", 25), Person("Pushpraj", 27))
    people.maxBy { it.age }

无法理解这里的问题。

标签: genericskotlinlambda

解决方案


TL;博士

people.maxBy(Person::age)会工作(看括号)

方法签名

maxBy函数具有以下签名:

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

如果你写 people.maxBy { Person::age },它可以写成people.maxBy( { Person::age } )这意味着你传递一个lambda,它返回另一个返回 INT 年龄的 lambda(供应商)。

换句话说:您在其他 lambda 中传递 (java Supplier) lambda 而不是实际的 (java Supplier) lambda。它看起来很混乱,因为如果方法中的最后一个参数是 lambda,您可以删除 Kotlin 中的普通括号。


推荐阅读