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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With