Scala - implicit conversion of Int to Numeric[Int]

前端 未结 2 759
挽巷
挽巷 2020-12-31 23:54

I\'ve created a class that can be parameterised by anything that can be converted to Numeric

class Complex[T <% Numeric[T]] (val real : T, val imag : T) {         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 00:46

    You are using it wrong. The correct usage is like this:

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

    It is the same difference as in between Ordered and Ordering. An Ordered[T] instance can be compared to T, while an Ordering[T] provides a method that compares a a couple of T.

提交回复
热议问题