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

我想创建具有以下属性的类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

在默认参数中调用默认构造函数是不可能的。

仅在内联函数中可用的泛化泛型