4 scala
我有以下课程:
case class Vec2(x: Int, y: Int) { def +(other: Vec2) = Vec2(x + other.x, y + other.y) }
case class Vec3(x: Int, y: Int, z: Int) { def +(other: Vec3) = Vec3(x + other.x, y + other.y, z + other.z) }
Run Code Online (Sandbox Code Playgroud)
以下方法:
def doStuff1(a: Vec2, b: Vec2) = (a, a + b)
def doStuff2(b: Vec3, b: Vec3) = (a, a + b)
Run Code Online (Sandbox Code Playgroud)
我的问题:如何以类型安全的方式将这两个函数合并为一个通用函数?可以以任何方式改变课程.
就像是
def doStuff[V](a: V, b: V) = (a, a + b)
Run Code Online (Sandbox Code Playgroud)
显然不会起作用,因为调用了"+"方法.我尝试了各种疯狂的东西(带有抽象类型的公共基类,显式类型的自引用,差异,......)但是无法提出解决方案.
我能想出的最好的想法是运行时检查(模式匹配或isInstanceOf/asInstanceOf),但这不符合类型安全要求.我只是想/希望必须有更好的方法来做到这一点.
Jor*_*tiz 20
trait Vector[V <: Vector[V]] { this: V =>
def +(other: V): V
}
case class Vec2(x: Int, y: Int) extends Vector[Vec2] {
override def +(other: Vec2): Vec2 = Vec2(x + other.x, y + other.y)
}
case class Vec3(x: Int, y: Int, z: Int) extends Vector[Vec3] {
override def +(other: Vec3): Vec3 = Vec3(x + other.x, y + other.y, z + other.z)
}
def doStuff[V <: Vector[V]](a: V, b: V): (V, V) = (a, a + b)
Run Code Online (Sandbox Code Playgroud)