T:Numeric
如果我是你,我会将 T 限制为 Numeric 类型,然后使用 zero 值作为空矩阵的默认值:
scala> :pa
// Entering paste mode (ctrl-D to finish)
import scala.reflect.ClassTag
class Matrix[T:Numeric](val structure: Array[Array[T]])
{
def *(that: Matrix[T]): Matrix[T] = ???
def +(that: Matrix[T]): Matrix[T] = ???
override def toString: String = structure.map(_.mkString(",")).mkString("\n")
}
object Matrix
{
def apply[T:Numeric:ClassTag](rows: Int, cols: Int): Matrix[T] =
{
val zero: T = implicitly[Numeric[T]].zero
new Matrix[T](Array.fill[T](rows, cols)(zero))
}
def apply[T:Numeric](data: Array[Array[T]]): Matrix[T] = new Matrix(data)
}
// Exiting paste mode, now interpreting.
import scala.reflect.ClassTag
defined class Matrix
defined object Matrix
scala> val empty = Matrix[Int](3,3)
empty: Matrix[Int] =
0,0,0
0,0,0
0,0,0
scala> val ex = Matrix[Int](Array(Array(1,2), Array(3,4)))
ex: Matrix[Int] =
1,2
3,4
T <: AnyRef
否则,如果您想使用null 作为默认值的非数字值,您可以执行以下操作:
scala> :pa
// Entering paste mode (ctrl-D to finish)
import scala.reflect.ClassTag
class Matrix[T >: Null <: AnyRef](val structure : Array[Array[T]])
{
override def toString: String = structure.map(_.mkString(",")).mkString("\n")
}
object Matrix
{
def apply[T >: Null <: AnyRef : ClassTag](rows: Int, cols: Int): Matrix[T] =
{
new Matrix[T](Array.fill[T](rows, cols)(null))
}
def apply[T >: Null <: AnyRef](data: Array[Array[T]]): Matrix[T] = new Matrix(data)
}
// Exiting paste mode, now interpreting.
import scala.reflect.ClassTag
defined class Matrix
defined object Matrix
scala> case class Person(name: String)
defined class Person
scala> val empty = Matrix[Person](3,3)
empty: Matrix[Person] =
null,null,null
null,null,null
null,null,null
scala> val data = Array(Array(Person("a"), Person("b")), Array(Person("c"), Person("d")))
data: Array[Array[Person]] = Array(Array(Person(a), Person(b)), Array(Person(c), Person(d)))
scala> val ex = Matrix[Person](data)
ex: Matrix[Person] =
Person(a),Person(b)
Person(c),Person(d)
请注意,您必须通过添加绑定的T >: Null 手动指定T 可以是Null 的超类型。