简体   繁体   English

Scala:两种方法,不同的参数类型但相同的代码:如何统一?

[英]Scala: Two methods, different parameter types but same code: How to unify?

I have the following classes: 我有以下课程:

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) }

And the following methods: 以下方法:

def doStuff1(a: Vec2, b: Vec2) = (a, a + b)
def doStuff2(b: Vec3, b: Vec3) = (a, a + b)

My question: How can I merge these two functions into one generic one in a type-safe manner? 我的问题:如何以类型安全的方式将这两个函数合并为一个通用函数? The classes may be altered in any way. 可以以任何方式改变课程。

Something like 就像是

def doStuff[V](a: V, b: V) = (a, a + b)

obviously won't work, because of the call to the "+" method. 显然不会起作用,因为调用了“+”方法。 I've tried all kinds of crazy stuff (common base class with abstract type, explicitly typed self references, variances, ...) but couldn't come up with a solution. 我已经尝试过各种疯狂的东西(带有抽象类型的常见基类,显式类型的自引用,差异,......)但是无法提出解决方案。

The best idea I could come up with is a runtime-check (pattern matching or isInstanceOf/asInstanceOf), but that doesn't satisfy the type safety requirement. 我能想出的最好的想法是运行时检查(模式匹配或isInstanceOf / asInstanceOf),但这不符合类型安全要求。 I just think/hope there must be a better way to do this. 我只是想/希望必须有更好的方法来做到这一点。

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)

You could try some kind of Structural Type . 你可以尝试某种结构类型 Like this: 像这样:

def doStuff[V <: {def +(other: V): V }](a: V, b: V) = (a, a + b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Scala:两个不同类的实例,相同的方法 - Scala: instances of two different classes, same methods Scala中类型较高的类型类实例中有两个参数函数,如何将这种简单的Haskell代码转换为Scala? - Two parameter functions in type class instances of higher kinded types in Scala, how to translate this simple Haskell code to Scala? 如何通过Scala / Java方法中的反射获取参数名称和类型? - How to get parameter names and types via reflection in Scala/Java methods? 为两种方法插入Scala代码 - To insert scala code for two methods 如何在scala中为不同类型的参数组合相同的函数 - How to combine the same function for different types of argument in scala 如何在Scala中计算具有两种不同数据类型的RPN表达式? - How to calculate a RPN expression having two different data types in Scala? 如何在Scala的一个解析器中解析两种不同的类型? - How to parse two different types in one parser in Scala? 为什么Scala的Traversable有两种类型略有不同的copyToArray方法? - Why does Scala's Traversable have two copyToArray methods with slightly different types? 在 scala spark 中统一两行 dataframe - unify two rows of a dataframe in scala spark Scala向左折叠两种参数类型 - Scala Fold Left with Two Parameter Types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM