Lanbo
Lanbo

Reputation: 15702

Scala Typing: How to Ensure Numeric Type

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?

Upvotes: 8

Views: 2147

Answers (1)

Madoc
Madoc

Reputation: 5919

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.

Upvotes: 11

Related Questions