我想创建具有以下属性的类 Matrix2D :
我怎么能这样做? 这是我的草图:
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 }) })
}
}
答案 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仅适用于内联函数。