[英]Scala: Value Class vs Case Class
I'm trying to discover the differences between using a value class or a case class in a given scenario. 我试图发现在给定方案中使用值类或案例类之间的区别。 Suppose I want to model the integers mod 5 as a unique datatype.
假设我想将整数mod 5建模为唯一的数据类型。 The question is which one I should begin with...
问题是我应该从哪开始...
class IntegerMod5(val value: Int) extends AnyVal
case class IntegerMod5(value: Int)
Regardless, it seems that I can create an implementation of Numeric
fairly easily. 无论如何,我似乎可以相当轻松地创建
Numeric
的实现。 With the case class approach, then, I can simply do this: 然后,使用案例类方法,我可以简单地做到这一点:
case class IntegerMod5(value: Int)(implicit ev: Numeric[IntegerMod5]) {
import ev.mkNumericOps
}
However, it seems to be a much more difficult endeavour with value classes, mainly as the benefit is to avoid object creation. 但是,使用值类似乎要困难得多,主要是因为这样做的好处是避免对象创建。 Thus, something like
因此,类似
implicit class IntegersMod5Ops(value: IntegerMod5)(implicit ev: Numeric[IntegerMod5]) {
import ev.mkNumericOps
}
Would appear to largely defeat the purpose. 看起来将大大挫败目标。 (Not sure if it even works, actually.)
(不确定它是否真的起作用。)
The question is that is it possible to use Numeric
with a value class, or will I have to bite the bullet and use a case class? 问题是,是否可以将
Numeric
与值类一起使用,还是我不得不硬着头皮使用案例类?
You don't need implicit ev: Numeric[IntegerMod5]
as an argument, just define it in the companion object: 您不需要
implicit ev: Numeric[IntegerMod5]
作为参数,只需在伴随对象中定义它:
object IntegerMod5 {
implicit val numeric: Numeric[IntegerMod5] = ...
}
It will be automatically picked up when you use arithmetic operations on IntegerMod5
s, and because it's a val
, it's only initialized once (you can use object
as well). 当您在
IntegerMod5
上使用算术运算时,它将被自动IntegerMod5
,并且由于它是一个val
,因此仅被初始化了一次(您也可以使用object
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.