【问题标题】:Is the Kotlin documentation correct?Kotlin 文档是否正确?
【发布时间】:2017-05-27 16:46:20
【问题描述】:

代码(如下所示)是否正确?取自 Kotlin-docs.pdf 的第 63 页,这也是 https://kotlinlang.org/docs/reference/generics.html 的最后一个代码 sn-p

 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 需要一个类型参数 2. 类型推断失败。预期类型不匹配:推断类型为 List,但预期为 List 3. 无法访问'clone':它在'Cloneable'中受到保护

通过将代码更改为以下内容,可以轻松解决前两个错误:

 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

我错过了什么吗?还是文档中有错误?

谢谢。

【问题讨论】:

标签: kotlin


【解决方案1】:

it.clone() 返回 Any 并且您会收到将 List 转换为 List 的错误。 因此,您已将其更改为 List。

您的下一个错误是无法访问克隆:它在 Cloneable 中受到保护

这个问题可以通过使用公共方法创建我们自己的Cloneable接口来解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2016-05-01
    • 2016-08-07
    • 1970-01-01
    • 2011-07-06
    相关资源
    最近更新 更多