Generics 如何在类构造函数中调用泛型类型的构造函数
我想创建具有以下属性的类Matrix2D:Generics 如何在类构造函数中调用泛型类型的构造函数,generics,kotlin,Generics,Kotlin,我想创建具有以下属性的类Matrix2D: 类应该是泛型的 应能够接受尽可能多的类型(理想情况下为所有类型) “Default”构造函数应使用默认类型值初始化所有单元格 当类型没有默认构造函数时,正确处理大小写(可能是默认参数解决了这个问题) 我怎么能做到? 这是我的素描: class Matrix2D<T> : Cloneable, Iterable<T> { private val array: Array<Array<T>>
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 }) })
}
}
类矩阵2d:可克隆、可移植{
私有val数组:数组
//调用默认的T()构造函数(如果存在)
//能够传递另一个类型的默认值
构造函数(行:Int,列:Int,默认值:T=T()){
什么时候{
行数<1->抛出MatrixDimensionException(“行数应>=1”)
列<1->抛出MatrixDimensionException(“列数应>=1”)
}
array=array(行,{array(列,{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() } }
}
}
类矩阵2d:可克隆、可移植{
私有val数组:数组
构造函数(行:Int,列:Int,默认值:T):
这(行、列、{default})
构造函数(行:Int,列:Int,工厂:()->T){
什么时候{
行数<1->抛出MatrixDimensionException(“行数应>=1”)
列<1->抛出MatrixDimensionException(“列数应>=1”)
}
数组=数组(行){数组(列){factory()}
}
}
请注意,在这种情况下不能使用
T
类型的数组,因为有关其实际类型的信息在运行时被擦除。只要使用Any
数组,并在必要时将实例强制转换为T
。这看起来像是如果我们使用Any
我们不需要第二个构造函数:构造函数(行:Int,列:Int,测试:T){当{rows<1->抛出MatrixDimensionException(“行数应>=1”)columns<1->throw MatrixDimensionException(“列数应大于等于1”)}array=array(行){array(columns){test as Any}}}}不是吗?这只是一个方便的构造函数,您可以删除它。实际上,它与任何都没有关系。