generics - 如何在类构造函数中调用泛型类型的构造函数

标签 generics kotlin

我想创建具有以下属性的类 Matrix2D:

  1. 类应该是通用的
  2. 应该能够接受尽可能多的类型(最好是全部)
  3. “默认”构造函数应使用默认类型值初始化所有单元格
  4. 正确处理大小写,当类型没有默认构造函数时(可能默认参数解决了这个问题)

我该怎么做? 这是我的草图:

class Matrix2D<T> : Cloneable, Iterable<T> {
    private val array: Array<Array<T>>
    // Call default T() constructor if it exists
    // Have ability to pass another default value of type
    constructor(rows: Int, columns: Int, default: T = T()) {
        when {
            rows < 1 -> throw MatrixDimensionException("Number of rows should >= 1")
            columns < 1 -> throw MatrixDimensionException("Number of columns should be >= 1")
        }
        array = Array(rows, { Array(columns, { default }) })
    }
}

最佳答案

没有办法在编译时检查一个类是否有默认构造函数。我会通过传递一个创建给定类型实例的工厂来解决这个问题:

class Matrix2D<T : Any> : Cloneable, Iterable<T> {
  private val array: Array<Array<Any>>

  constructor(rows: Int, columns: Int, default: T) :
      this(rows, columns, { default })

  constructor(rows: Int, columns: Int, factory: () -> T) {
    when {
      rows < 1 -> throw MatrixDimensionException("Number of rows should >= 1")
      columns < 1 -> throw MatrixDimensionException("Number of columns should be >= 1")
    }
    array = Array(rows) { Array<Any>(columns) { factory() } }
  }
}

请注意,在这种情况下,您不能使用 T 类型的数组,因为有关其实际类型的信息在运行时会被删除。只需使用 Any 数组并在必要时将实例转换为 T

关于generics - 如何在类构造函数中调用泛型类型的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36428819/

相关文章:

java - 如何避免接口(interface)的通用编译器警告

Java 推断类型化 HashSet 的类型错误

ios - 如何在 iOS 中自己创建的模型类中使用泛型?

javascript - 从 kotlin 创建新的 Node 模块对象

android - 在 Kotlin 构造函数参数中什么情况下需要 val/var?

Android 绑定(bind)适配器不适用于 CustomView

Android Studio 代码覆盖率未显示任何 Kotlin 类

Java 反射通用类型 ParamertizedType 对象创建失败并出现 java.lang.exception

swift - Eureka : cannot convert value of type 'BaseRow?' to specified type 'CustomPushRow?'

firebase - FireStore Tasks.whenAllComplete 与协程