I thinks it's easier to explain it with a simple example. (help rephrasing the title is welcome ;-)
I'd like to implement a squared
method and, using implicit def
, automatically add it to any class that supports the *
-operator.
With an Int it's very easy:
class EnhancedInt(x: Int) { def squared = x * x }
implicit def IntToEnchancedInt(x: Int) = new EnhancedInt(x)
But with Any or AnyVal I get the following error:
scala> class EnhanceAny(x: AnyVal) { def squared = x * x }
<console>:7: error: value * is not a member of AnyVal
class EnhanceAny(x: AnyVal) { def squared = x * x }
I'd like to know how I could apply it to any numeric class, or, even better, to any class supporting the *
-operator.