Eugene Barsky
Eugene Barsky

Reputation: 6012

Scala: Function argument Int or Double, how to make it generic?

I'm almost sure there is already an answer, but being a beginner in Scala I cannot find it.

So, I've made a power function of two arguments:

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)
}

If I then calculate power(2, 3)

  println(
    power(2, 3)
  )

I get 8.0, which is OK, but it would be better to have just 8 if the first argument is Int. How can I achieve that?

Upvotes: 1

Views: 652

Answers (1)

SwiftMango
SwiftMango

Reputation: 15304

You can use Numeric

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

The magic of type class

Upvotes: 5

Related Questions