【问题标题】:Member reference not working for maxBy in Kotlin immutable list成员参考不适用于 Kotlin 不可变列表中的 maxBy
【发布时间】:2020-01-24 10:51:51
【问题描述】:

这是我的代码不起作用:

    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 }

无法理解这里的问题。

【问题讨论】:

    标签: generics kotlin lambda


    【解决方案1】:

    TL;DR

    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,它返回另一个lambda(供应商),它返回INT年龄。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多