scala type mismatch with shorts and multiplication

126 views Asked by At

I have two functions that find the factorial of a number and one works using integers, but the second using only shorts yield an error. This is the code

var fac16i: Function2[Short, Short, Short] = new Function2[Short, Short, Short] {
    @tailrec override def apply (x: Short, acc: Short = 1): Short = {
      if (x.toShort <= 1.toShort) acc.toShort
      else apply(x - 1, x  * acc)
    }
  }

  var fac32i: Function2[Int, Int, Int] = new Function2[Int, Int, Int] {
    @tailrec override def apply (x:Int, acc:Int=1): Int = {
      if (x<=1) acc
      else apply(x-1, x * acc)
    }
  }

Can someone help me with this. Note: I am using scala-native.

1

There are 1 answers

0
jwvh On

Move the .toShort casting from where it's not needed to where it is needed.

if (x <= 1) acc
else apply((x-1).toShort, (x*acc).toShort)