8

I have a small problem in Scala with a typing matter. In Haskell, I can do this:

add :: (Num a) => (a,a) -> (a,a) -> (a,a)

That way, I can throw into add any type that is a numeric and supports + etc. I want the same for a Scala class, like so:

case class NumPair[A <: Numeric](x: A, y: A)

But that does not seem to work. But due to the Scala Docs, Numeric[T] is the only trait that allows for these operations, and seems to be extended by Int, Float etc.

Any tips?

Lanbo
  • 15,118
  • 16
  • 70
  • 147

1 Answers1

11
case class NumPair[A](x:A, y:A)(implicit num:Numeric[A])

The Numeric instance itself is not extended by Int, Float, etc., but it is provided as an implicit object. For a longer explanation, see here.

Community
  • 1
  • 1
Madoc
  • 5,841
  • 4
  • 25
  • 38
  • I am not sure if I should like `implicit`s - they're quite nice if you want to save work, but often they destroy the typing system by obscuring the type inference. – Lanbo Mar 16 '11 at 18:13
  • 1
    In which way would implicits obscure type inference? - If you wish, you can make the `Numeric` instance an explicit parameter, but then you would always have to pass it in explicitly, which is really redundant for types like `Int`, `Float`, etc. With implicits, you have the choice of whether or not you'd like to pass it explicitly. – Madoc Mar 16 '11 at 21:19