【问题标题】:Kotlin generic type, Type inference failedKotlin 泛型类型,类型推断失败
【发布时间】:2018-05-15 07:10:06
【问题描述】:

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&lt;T&gt;
找到:List&lt;Any&gt;

为什么这个例子不能编译?

【问题讨论】:

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


    【解决方案1】:

    问题在于clone() 的使用,正如编译器所抱怨的那样,它是protected。这个问题已经在这里讨论过了:https://discuss.kotlinlang.org/t/is-the-documentation-correct/2925

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2020-12-30
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多