Scala - implicit conversion of Int to numeric [Int]

I created a class that can be parameterized by anyone that can be converted to numeric

class Complex[T <% Numeric[T]] (val real : T, val imag : T) { //... complex number methods ... } 

Then in another place in the code I try:

 var myComplex = new Complex(0, 1) 

This causes a compilation error because (surprisingly) there is no implicit conversion between Int and Numeric [Int] or even between Int and Integral [Int].

Am I missing something? Is there an implicit conversion somewhere I don't see?

There is an implicit object called IntIsIntegral defined in Numeric.scala. I tried using this to create my own implicit conversion method:

 def implicit intToNumericInt(val i : Int)(implicit n : IntIsIntegral) = n.fromInt(i) 

I am surprised that this is necessary and, in any case, this leads to infinite recursion into the .fromInt method.

I am sure that I am missing something basic (as you can tell, I am new to Scala), so I would rate the point in the right direction.

As you can see from the example, I'm trying to get a complex number job that can accept and work with any numeric type. I hope to contribute to the scalala (linear algebra) project. After that, I want to introduce "Titt", which describes the responsibilities of the elements in the matrix (basically, just the + and * operators) and the re-equipment of support for complex numbers in the matrix manipulation library.

+4
source share
2 answers

You are using it incorrectly. Proper use looks like this:

 class Complex[T](val real : T, val imag : T)(implicit num: Numeric[T]) { import num._ // make implicit conversions available //... complex number methods ... } 

This is the same difference as between Ordered and Ordering . An instance of Ordered[T] can be compared to T , and Ordering[T] provides a method that compares a pair of T

+9
source

In Scala 2.8, it can also be written as

 class Complex[T: Numeric] (val real : T, val imag : T) { def +(that: Complex[T]) = { val r = implicitly[Numeric[T]].plus(this.real, that.real) val i = implicitly[Numeric[T]].plus(this.imag, that.imag) new Complex(r, i) } } 

This syntax is admittedly a bit tight, but it can be made more readable as follows:

 class Complex[T: Numeric] (val real : T, val imag : T) { val num = implicitly[Numeric[T]] def +(that: Complex[T]) = { new Complex(num.plus(this.real, that.real), num.plus(this.imag, that.imag)) } } 

The declaration of class C[T: M]( ... ) { val x = implicitly[M[T]] seems equivalent to class C[T]( ... )(implicit x: M[T]) { import x._ as noted in the comments to the previous decision. This is not just syntactic sugar, because there are differences in how it compiles, for example. in the first case, x is a method, and in the second case, a field.

+2
source

All Articles