In order to extend value classes, you need to recapture the underlying type. Since value classes are required to have their wrapped type accessible (val i
not just i
above), you can always do this. You can't use the handy implicit class
shortcut, but you can still add the implicit conversion longhand. So, if you want to add a -
method to Meter
you must do something like
class RichMeter(val meters: Double) extends AnyVal {
def -(m: Meter) = new Meter(meters - m.meters)
}
implicit def EnrichMeters(m: Meter) = new RichMeter(m.meters)
Note also that you are allowed to (freely) rewrap any parameters with the original value class, so if it has functionality that you rely on (e.g. it wraps a Long
but performs complicated bit-mixing), you can just rewrap the underlying class in the value class you're trying to extend wherever you need it.
(Note also that you'll get a warning unless you import language.implicitConversions
.)
Addendum: in Scala 2.11+, you may make the val
private; for cases where this was done, you will not be able to use this trick.