Scala:两种方法,不同的参数类型但相同的代码:如何统一?
发布时间:2020-12-16 18:26:15 所属栏目:安全 来源:网络整理
导读:我有以下课程: 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) } 以下方法: def doStuff1(a: Vec2,b:
我有以下课程:
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) } 以下方法: def doStuff1(a: Vec2,b: Vec2) = (a,a + b) def doStuff2(b: Vec3,b: Vec3) = (a,a + b) 我的问题:如何以类型安全的方式将这两个函数合并为一个通用函数?可以以任何方式改变课程. 就像是 def doStuff[V](a: V,b: V) = (a,a + b) 显然不会起作用,因为调用了“”方法.我尝试了各种疯狂的东西(带有抽象类型的公共基类,显式类型的自引用,差异,……)但是无法提出解决方案. 我能想出的最好的想法是运行时检查(模式匹配或isInstanceOf / asInstanceOf),但这不符合类型安全要求.我只是想/希望必须有更好的方法来做到这一点. 解决方法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,z: Int) extends Vector[Vec3] { override def +(other: Vec3): Vec3 = Vec3(x + other.x,z + other.z) } def doStuff[V <: Vector[V]](a: V,b: V): (V,V) = (a,a + b) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |