Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
Lanbo Avatar asked Mar 16 '11 16:03

Lanbo


People also ask

How do you define type in Scala?

Scala is a statically typed programming language. This means the compiler determines the type of a variable at compile time. Type declaration is a Scala feature that enables us to declare our own types.

How does Scala determine types when they are not specified?

For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type. Non-value types are expressed indirectly in Scala.

What does <: mean in Scala?

It means an abstract type member is defined (inside some context, e.g. a trait or class), so that concrete implementations of that context must define that type.

How do you find the data type of a variable in Scala?

Use the getClass Method in Scala The getClass method in Scala is used to get the class of the Scala object. We can use this method to get the type of a variable. The output above shows that it prints java. lang.


1 Answers

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.

like image 79
Madoc Avatar answered Oct 14 '22 09:10

Madoc