代码(如下所示)是否正确?它取自 Kotlin-docs.pdf 的第 63 页,这也是 https://kotlinlang.org/docs/reference/generics.html 的最后一个代码片段。
fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T>
where T : Comparable, T : Cloneable {
return list.filter { it > threshold }.map { it.clone() }
}
按照原样,编译器失败并显示: 1. kotlin 中定义的 Comparable 接口(interface)需要一个类型参数 2. 类型推断失败。预期类型不匹配:推断类型为 List 但预期为 List 3. 无法访问“克隆”:它在“可克隆”中受到保护
通过将代码更改为以下内容,可以轻松解决前两个错误:
fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<Any>
where T : Comparable<in T>, T : Cloneable {
return list.filter { it > threshold }.map { it.clone() }
}
我仍然收到以下错误: 无法访问“克隆”:它在“可克隆”中受到保护
我正在使用 Kotlin 1.1.2-release-IJ2017.1-1
我错过了什么吗?还是文档中有错误?
谢谢。
最佳答案
it.clone()
返回 Any
并且您将 List 转换为 List 时出错。
因此,您已将其更改为列表。
您的下一个错误是无法访问克隆:它在可克隆中受到保护。
这个问题可以通过使用公共(public)方法创建我们自己的 Cloneable 接口(interface)来解决。
关于kotlin - Kotlin 文档是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44219340/