【问题标题】:Using generic type of interface in method在方法中使用泛型接口
【发布时间】:2017-11-12 16:51:42
【问题描述】:

我对 Kotlin 中的泛型感到困惑。如何在函数参数中使用 T 类型的 Class(在 addNewItem() 和 deleteItem() 中)?我收到错误“类型参数 T 被声明为 'out' 但出现在 'in' 位置 kotlin”

interface IStorageManager<out T: IFileItem> {

fun getAllItems(): List<T>

fun addNewItem(itemToAdd: T)

fun deleteItem(itemToDelete: T)

}

screen

【问题讨论】:

    标签: generics kotlin


    【解决方案1】:

    如果您的界面只生成T,您可以通过使用out 对其进行注解来向编译器说明这一点。在您的示例中,您还有充当T 消费者的方法,因此out 不起作用。只需删除 out 关键字,一切都会正常工作。

    这是一个很好的参考: https://kotlinlang.org/docs/reference/generics.html

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 2021-04-17
      • 2011-03-14
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多