generics - 成员参考不适用于 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 }
无法理解这里的问题。
解决方案
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 中的普通括号。
推荐阅读
- php - Symfony 3.4 中的删除/截断表无法正常工作
- c++ - 在 Qt 上添加小部件并将它们排列到屏幕的角落
- vue.js - 路由更改时元素上的 Vue 转换
- javascript - 如何关闭通过另一个函数的 polyfill 生成的 showModalDialog()?
- java - XML 文件解析的文件过早结束异常经常发生但不经常发生。
- json - 更新 json 文件中的数据
- python - 在 pycharm (pygame) 中运行 pyTMX 时出现 TypeError
- joomla - 登录 Joomla 后端时出现错误 503?
- javascript - 使用 Javascript 进行字符串切割
- sql - odbc 调用失败 [microsoft] [sql server native client 11.0] [sql server] 卷起的多部分标识符未绑定