Generic implicit class that applies both to Int and Long
scala
Solution
What you have looks pretty close. A few comments:
The type class you want is `Integral`, not `Numeric`.
Instead of writing the context bound as `[A: Integral]`, put an implicit parameter on the constructor, so you can import `mkNumericOps` from that object:
implicit class SuperNumber[A](i: A)(implicit integral: Integral[A]) {
import integral._
Problem
I wanted to create a "pimp my type" for natural numbers in Scala by adding some helper methods. My first attempt was to create one for `Int` and one for `Long` (and later one for `BigInt` perhaps too) ``` implicit class SuperInt(n:Int) { def square = n * n def pow(m: Int) = math.pow(n,m) def **(m: Int) = pow(m) def sqrt = math.sqrt(n) def isEven = dividesBy(2) def isOdd = !isEven def dividesBy(m:Int) = n % m == 0 } implicit class SuperLong(n:Long) { def square = n * n def pow(m: Int) = math.pow(n,m) def **(m: Int) = pow(m) def sqrt = math.sqrt(n) def isEven = dividesBy(2) def isOdd = !isEven def dividesBy(m:Int) = n % m == 0 } ``` Exactly the same code of course, not too DRY, and doesn't "feel" right. So my question is - what is the (idiomatic) Scala way to do this for Long, Int and BigInt all at once? p.s. Here is what I tried so far, it sort of works, but I'm pretty sure it's not idiomatic and has a lot of issues. The following a result of reading a little bit about "type classes" here (which I still don't fully feel I 100% understand) so this is the result (If your eyes hurt, please forgive me, I'm relatively new to Scala) ``` implicit class SuperNumber[A : Numeric](i: A) { import Numeric.Implicits._ def squared: A = i * i def pow(m: Int) = math.pow(i.toDouble(),m) def **(m: Int) = pow(m) def sqrt = math.sqrt(i.toDouble()) def isEven = dividesBy(2) def isOdd = !isEven def dividesBy(m:Int) = { i match { case n @ (_:Int | _:Long) => n.toLong() % m == 0 case other => { val asDouble = other.toDouble() val asLong = other.toLong() if (asDouble == asLong) { asLong % m == 0 } else { false } } } } } ``` (I added "support" for non Int and Long as it didn't seem too hard)