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

时间:2016-04-05 14:10:10

标签: generics kotlin

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

  1. 类应该是通用的
  2. 应该能够接受尽可能多的类型(理想情况下全部)
  3. “默认”构造函数应初始化所有具有默认类型值的单元格
  4. 正确处理大小写,当类型没有默认构造函数时(可能是默认参数解决了这个问题)
  5. 我怎么能这样做? 这是我的草图:

    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 }) })
        }
    }
    

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

无法在默认参数中调用默认构造函数。

Reified generics仅适用于内联函数。

相关问题