Reputation: 51271
This simplified (and somewhat contrived) example is pretty close to what I'm looking for.
implicit class PlusMinus(a: Double) {
def +-(b: Double) = if (a > b) a-b else a+b
}
With this I can:
scala> 3 +- 4L
res0: Double = 7.0
scala> 5f +- 1
res1: Double = 4.0
scala> 7L +- 6f
res3: Double = 1.0
But I have to wonder:
Every result is a Double. Can I imitate the automatic number conversions in the standard library?
Int +- Int = Int
Long +- Long = Long
Long +- Float = Float // etc.
Is there a better way? (There's always a better way.)
Upvotes: 0
Views: 61
Reputation: 938
You could implement your operator like this
implicit class PlusMinus[T](a: T)(implicit ev : Numeric[T]) {
def +-(b: T) = if (ev.gt(a, b)) ev.minus(a, b) else ev.plus(a , b)
}
This quick solution has a problem, it'ok only with the same type in the two operands.
This one seems to respond to your problem :
implicit class PlusMinus[T](a: T)(implicit ev : Numeric[T]) {
def +-(b: Double) = {
val ad = ev.toDouble(a)
if (ad > b) ad - b else ad + b
}
def +-(b: Long) = {
val ad = ev.toLong(a)
if (ad > b) ad - b else ad + b
}
def +-(b: Int) = {
val ad = ev.toInt(a)
if (ad > b) ad - b else ad + b
}
def +-(b: Float) = {
val ad = ev.toFloat(a)
if (ad > b) ad - b else ad + b
}
}
We have that result
3 +- 4 //> res0: Int = 7
3 +- 4L //> res1: Long = 7
3L +- 4 //> res2: Int = 7
You can see in the last one, that the result type is the type of the second operand.
Upvotes: 1