Scala:函数参数 Int 或 Double,如何使其通用?

Eug*_*sky 1 generics scala

我几乎可以肯定已经有了答案,但是作为 Scala 的初学者,我找不到它。

因此,我创建了一个power包含两个参数的函数:

def power(x: Double, n: Int): Double = {
  @scala.annotation.tailrec
  def go(acc: Double, i: Int): Double = {
    if (i == 0) acc
    else go(acc * x, i - 1)
    }

  go(1, n)
}
Run Code Online (Sandbox Code Playgroud)

如果我然后计算 power(2, 3)

  println(
    power(2, 3)
  )
Run Code Online (Sandbox Code Playgroud)

我明白了8.0,这很好,但8如果第一个参数是,那就更好了Int。我怎样才能做到这一点?

tex*_*uce 5

您可以使用数字

def power[T](x: T, n: Int)(implicit num: Numeric[T]): T = {
  import num._
  @scala.annotation.tailrec
  def go(acc: T, i: Int): T = {
    if (i == 0) acc
    else go(acc * x, i - 1)
    }

  go(fromInt(1), n)
}

power(2, 3) // 8: Int
Run Code Online (Sandbox Code Playgroud)

类型类的魔力