Scala: generic function multiplying Numerics of different types

后端 未结 1 1603
盖世英雄少女心
盖世英雄少女心 2021-01-02 18:51

I am trying to write a generic weighted average function. I want to relax the requirements on the values and the weights being of the same type. ie, I want to support seque

相关标签:
1条回答
  • 2021-01-02 19:26

    I think you're making this harder than it needs to be.

    You need "evidence" that both parameters are Numeric. With that established let the evidence do the work. Scala will employ numeric widening so that the result is the more general of the two received types.

    def mult[T](a: T, b: T)(implicit ev:Numeric[T]): T =
      ev.times(a,b)
    

    If you want to get a little fancier you can pull in the required implicits. Then it's a little easier to read and understand.

    def mult[T: Numeric](a: T, b: T): T = {
      import Numeric.Implicits._
      a * b
    }
    

    Proof:

    mult(2.3f , 7)  //res0: Float = 16.1
    mult(8, 2.1)    //res1: Double = 16.8
    mult(3, 2)      //res2: Int = 6
    

    For more on generic types and numeric widening, this question, and its answer, are worth studying.

    0 讨论(0)
提交回复
热议问题