Kotlin泛型类型,类型推断失败

时间:2017-12-01 08:01:34

标签: android android-studio kotlin android-studio-3.0

Kotlin参考文件说这个例子是有效的。

https://kotlinlang.org/docs/reference/generics.html#upper-bounds

fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T>
    where T : Comparable<T>,
          T : Cloneable {
  return list.filter { it > threshold }.map { it.clone() }
}

但在Android studio 3.0中,它在it.clone()下显示细红线。错误信息是:

  

类型推断失败。预期的类型不匹配。
必填:List<T>   
发现:List<Any>

为什么这个例子无法编译?

1 个答案:

答案 0 :(得分:1)

问题是使用clone(),编译器抱怨protected。问题已经在这里讨论过:https://discuss.kotlinlang.org/t/is-the-documentation-correct/2925