【问题标题】:Create a generic class with an array of type Comparable<T> in kotlin?在 kotlin 中创建一个具有 Comparable<T> 类型数组的泛型类?
【发布时间】:2016-07-11 05:03:17
【问题描述】:

Create generic 2D array in Kotlin 的启发,我有以下代码,它创建了一个类型为 T 的数组的泛型类。但是,一旦我添加了一个上限,就会出现编译错误。有没有办法做到这一点?

//This code compiles:
class GenericClass<T> protected constructor(size : Int, arrayFactory: (Int) -> Array<T>) {
  companion object {
    inline fun <reified T> invoke(size : Int)
       = GenericClass(size, { size -> arrayOfNulls<T>(size) })
  }
  val array = arrayFactory(size)
}

//Compile errors:
class GenericClass<T : Comparator<T>> protected constructor(size : Int, arrayFactory: (Int) -> Array<T>) {
  companion object {
    inline fun <reified T : Comparator<T>> invoke(size : Int)
       = GenericClass(size, { size -> arrayOfNulls<T>(size) })
  }
  val array = arrayFactory(max)
}

编译错误是:

  • 构造函数 GenericClass 中为 T 绑定的类型参数>(size: Int, arrayFactory: (Int) -> Array) 不满足:推断类型 T?不是 Comparator 的子类型

【问题讨论】:

    标签: generics kotlin


    【解决方案1】:

    错误消息虽然具有误导性,但确实暗示它与类型参数和参数的可空性约束有关。更改GenericClass 构造函数以允许nullArray 中,如下所示:

    class GenericClass<T : Comparator<T>> 
      protected constructor(size : Int, arrayFactory: (Int) -> Array<T?>) {
        companion object {
            inline fun <reified T : Comparator<T>> invoke(size : Int)
                = GenericClass(size, { size -> arrayOfNulls<T>(size) })
        }
        val array = arrayFactory(size)
    }
    

    arrayOfNulls 顾名思义创建给定size 的数组,其中填充nulls。因此,如果您想使用它,arrayFactory 需要接受它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多