scala - 为什么我不能在 Scala 中使用泛型类型约束?
问题描述
为什么我不能在 Scala 中使用泛型类型约束?这是我的代码
abstract class Adder[T]{
def +(a: Matrix[T], that: Matrix[T]): Matrix[T]
def *(a: Matrix[T], that: Matrix[T]): Matrix[T]
def show(a: Matrix[T]): Unit
}
object Adder{
implicit object TDouble extends Adder[T <: Double] {
override def +(a: Matrix[T], that: Matrix[T]): Matrix[T] = {
if (that.M != a.M || that.N != a.N) throw new RuntimeException("Illegal matrix dimensions.");
var C = Array.ofDim[T](a.M,a.N);
for (i <- 0 to a.M - 1)
for (j <- 0 to a.N - 1){
C(i)(j) = a.matrix(i)(j) + that.matrix(i)(j);
}
new Matrix(C)
}
}
}
这是错误
scala:11: error: ']' expected but ':' found.
implicit object TDouble extends Adder[T: <: Double] {
我希望在此对象中处理所有数字类型
解决方案
也许这接近你想要的?
import scala.reflect.ClassTag
//this is just a guess at what your Matrix might look like
class Matrix[A](val matrix :Array[Array[A]]) {
val M:Int = matrix.length
val N:Int = matrix.head.length
}
implicit class MatrixOps[T:Numeric:ClassTag](a :Matrix[T]) {
val nOps = implicitly[Numeric[T]]
import nOps._
def +(that :Matrix[T]) :Matrix[T] = {
if (that.M != a.M || that.N != a.N)
throw new RuntimeException("Illegal matrix dimensions.")
val c = Array.ofDim[T](a.M, a.N)
for (i <- 0 until a.M)
for (j <- 0 until a.N)
c(i)(j) = a.matrix(i)(j) + that.matrix(i)(j)
new Matrix(c)
}
}
有了这个,您应该能够添加任何两个 Matrix 实例,只要尺寸和数字类型(Int
,Float
等)匹配。
推荐阅读
- reactjs - 具有联合类型和泛型的打字稿数组要求字段是可选的才能编译
- python - PySide2:如何防止 QFileDialog 关闭 Sub-QMainWidget
- javascript - 如何创建全局安装到系统中的 CLI 应用程序,例如 ng?
- javascript - 我如何在 Node.js Web 服务器上根据请求生成 SPA 构建(例如,根据用户“发布”请求)并将构建文件上传到 S3?
- google-apps-script - Google Apps 脚本错误:“您无权访问请求的文档”
- android - 为什么调用 MediaStore.ACTION_IMAGE_CAPTURE 意图后图像的路径为空?
- java - 为什么我在 Spring Boot 应用程序中遇到此异常?
- laravel - Laravel Eloquent:获取任务完成百分比
- python-3.x - 从 LSTM 自动编码器馈送分类器数据
- javascript - 类型 '((instance: HTMLDivElement | null) => void) | 上不存在属性 'current' 参考对象
'