我想创建具有以下属性的类 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 }) })
}
}
最佳答案
没有办法在编译时检查一个类是否有默认构造函数。我会通过传递一个创建给定类型实例的工厂来解决这个问题:
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/