如何使用 Value[T : Numeric] 使代码更加“灵活”;就像“未装箱的”一样同行?

发布于 2024-12-07 20:36:01 字数 565 浏览 0 评论 0原文

如果我有像 5 * 5.0 这样的代码,结果将转换为最准确的类型 Double

但这似乎不适用于像

case class Value[T : Numeric](value: T) {
    type This = Value[T]
    def +(m: This) = Value[T](implicitly[Numeric[T]].plus(value, m.value))
    ...
}

implicit def numToValue[T : Numeric](v: T) = Value[T](v)

Is there a way to make things like someIntValue + double 工作,其中 someIntValue is Value[Int] 和 doubleDouble

PS:很抱歉这个标题远不完美。我感谢您提出更好措辞的建议......

If I have code like 5 * 5.0 the result gets converted to the most accurate type, Double.

But this doesn't seem to work with code like

case class Value[T : Numeric](value: T) {
    type This = Value[T]
    def +(m: This) = Value[T](implicitly[Numeric[T]].plus(value, m.value))
    ...
}

implicit def numToValue[T : Numeric](v: T) = Value[T](v)

Is there a way to make things like someIntValue + double work, where someIntValue is Value[Int] and double is Double?

PS: Sorry for the far less-than-perfect title. I'm thankful for suggestions for better wording ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦与时光遇 2024-12-14 20:36:01

您可以通过创建隐式运算符来做到这一点(需要大量的工作):

abstract class Arith[A,B,C] {
  def +(a: A, b: B): C
  def -(a: A, b: B): C
  def *(a: A, b: B): C
  def /(a: A, b: B): C
}
implicit object ArithIntLong extends Arith[Int,Long,Long] {
  def +(a: Int, b: Long) = a+b
  def -(a: Int, b: Long) = a-b
  def *(a: Int, b: Long) = a*b
  def /(a: Int, b: Long) = a/b
}
...
def f[A,B,C](a: A, b: B)(implicit arith: Arith[A,B,C]) = arith.*(a,b)


scala> f(5,10L)
res46: Long = 50

但您确实需要做的比这更多,因为您需要 A 和 B 单独的数字等价物,并且需要以两种方式定义非对称操作。鉴于涉及三种类型,专门化并不实际。

You can do this (with a lot of busywork) by creating implicit operators:

abstract class Arith[A,B,C] {
  def +(a: A, b: B): C
  def -(a: A, b: B): C
  def *(a: A, b: B): C
  def /(a: A, b: B): C
}
implicit object ArithIntLong extends Arith[Int,Long,Long] {
  def +(a: Int, b: Long) = a+b
  def -(a: Int, b: Long) = a-b
  def *(a: Int, b: Long) = a*b
  def /(a: Int, b: Long) = a/b
}
...
def f[A,B,C](a: A, b: B)(implicit arith: Arith[A,B,C]) = arith.*(a,b)


scala> f(5,10L)
res46: Long = 50

but you really have to do more than that, since you need a Numeric equivalent for A and B alone, and the asymmetric operations need to be defined both ways. And it's not really practical to specialize given that there are three types involved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文