Scala:两种方法,不同的参数类型但相同的代码:如何统一? [英] Scala: Two methods, different parameter types but same code: How to unify?

查看:35
本文介绍了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) }

以及以下方法:

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.

类似的东西

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.

我能想到的最好的主意是运行时检查(模式匹配或 isInstanceOf/asInstanceOf),但这并不能满足类型安全要求.我只是认为/希望必须有更好的方法来做到这一点.

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

这篇关于Scala:两种方法,不同的参数类型但相同的代码:如何统一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆