Why does Numeric behave differently than Ordered?

后端 未结 3 1691
無奈伤痛
無奈伤痛 2021-02-14 09:23

Scala has a number of traits that you can use as type classes, for example Ordered and Numeric in the package scala.math.

I can, f

3条回答
  •  無奈伤痛
    2021-02-14 10:24

    You can reduce Miles' solution to only use 1 extra line by doing this:

    Add an implicit conversion from A : Numeric to Numeric[A]#Ops

    object Ops {
      implicit def numeric[A : Numeric](a: A) = implicitly[Numeric[A]].mkNumericOps(a)
    }
    

    Then bring this into scope in your method

    def g[T : Numeric](a: T, b: T) = {
      import Ops.numeric
      a * b
    }
    

    See Scala ticket 3538 for more info.

提交回复
热议问题