I am trying to add numeric operations to a value class that I have defined called Quantity
. Code that I am using this is as follows...
import scala.language.implicitConversions
case class Quantity(value: Double) extends AnyVal
object Quantity {
implicit def mkNumericOps(lhs: Quantity): QuantityIsNumeric.Ops = QuantityIsNumeric.mkNumericOps(lhs)
}
object QuantityIsNumeric extends Numeric[Quantity] {
def plus(x: Quantity, y: Quantity): Quantity = Quantity(x.value + y.value)
def minus(x: Quantity, y: Quantity): Quantity = Quantity(x.value - y.value)
def times(x: Quantity, y: Quantity): Quantity = Quantity(x.value * y.value)
def negate(x: Quantity): Quantity = Quantity(-x.value)
def fromInt(x: Int): Quantity = Quantity(x.toDouble)
def toInt(x: Quantity): Int = x.value.toInt
def toLong(x: Quantity): Long = x.value.toLong
def toFloat(x: Quantity): Float = x.value.toFloat
def toDouble(x: Quantity): Double = x.value
def compare(x: Quantity, y: Quantity): Int = x.value compare y.value
}
I use this code as follows...
class SortedAskOrders[T <: Tradable] private(orders: immutable.TreeSet[LimitAskOrder[T]], val numberUnits: Quantity) {
def + (order: LimitAskOrder[T]): SortedAskOrders[T] = {
new SortedAskOrders(orders + order, numberUnits + order.quantity)
}
def - (order: LimitAskOrder[T]): SortedAskOrders[T] = {
new SortedAskOrders(orders - order, numberUnits - order.quantity)
}
def head: LimitAskOrder[T] = orders.head
def tail: SortedAskOrders[T] = new SortedAskOrders(orders.tail, numberUnits - head.quantity)
}
...when I try and compile this code I get the following error..
Error:(29, 63) type mismatch;
found : org.economicsl.auctions.Quantity
required: String
new SortedAskOrders(orders + order, numberUnits + order.quantity)
The following implementation of the +
method which explicitly uses implicit conversions (which I thought should already be in scope!) works.
def + (order: LimitAskOrder[T]): SortedAskOrders[T] = {
new SortedAskOrders(orders + order, Quantity.mkNumericOps(numberUnits) + order.quantity)
}
The compiler does not seem to be able to find the implicit conversion for the numeric +
operator. Thoughts?
I thought that it would be pretty standard to use implicit conversions and the Numeric
trait to create numeric operations for a value class. What am I doing wrong?
import Quantity._
on top of your file – Yuriy Gatilin-
,*
, etc.) appear to compile without complaint. No, it's pretty obvious that the compiler isn't looking for the implicit because+
is the string concat op and, since everything has a string representation, it doesn't need the implicit. I know of at least one work-around but I was hoping someone with deeper understanding of this would jump in with a clean and simple means of turning off the string-concat. – jwvh