Adding `squared` to Scala Numbers with Implicts and Type Classes

  1. We bring infixNumericOps into scope.
  2. We then invoke i * i, which is equivalent to i.*(i).
  3. The * can’t be found on i since i is of type A.
  4. However, now that we have infixNumericOps in scope, the compiler can use that conversion to create an instance of Numeric[A]#Ops.
  5. Numeric[A]#Ops does have * defined for type A, thus, a new Ops is constructued, holding our value i within it.
  6. The compiler then applies the * operator to to the second value of i and we’re done.

Cooler, but a hell of a lot more complicated to explain :)

Page 2 of 2 | Previous page