如何使用 Value[T : Numeric] 使代码更加“灵活”;就像“未装箱的”一样同行?
如果我有像 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] 和
double
是 Double
?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过创建隐式运算符来做到这一点(需要大量的工作):
但您确实需要做的比这更多,因为您需要 A 和 B 单独的数字等价物,并且需要以两种方式定义非对称操作。鉴于涉及三种类型,专门化并不实际。
You can do this (with a lot of busywork) by creating implicit operators:
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.