Type mismatch error of Unit instead of Int (Scala)
I'm new to Scala and I'm trying to define a tail recursion factorial function like this:
def anotherFactorial(n: Int): Int = {
def factHelper(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else factHelper(x - 1, x * accumulator)
factHelper(n, 1)
}
}
But it gives me a mismatch error saying that it found a Unit type instead of an Int and I cannot see how, I've checked other Scala questions with the same error (like this one: Scala Type Mismatch Unit Instead of Int) but doesn't seem I'm making those mistakes.
This is the error message:
type mismatch;
found : Unit
required: Int
}
Wrong brackets. You have:
def anotherFactorial(n: Int): Int = {
// the body with only def is Unit
def factHelper(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else factHelper(x - 1, x * accumulator)
factHelper(n, 1)
}
}
rather than
def anotherFactorial(n: Int): Int = {
// the body with only def is Unit
def factHelper(x: Int, accumulator: Int): Int = {
if (x <= 1) accumulator
else factHelper(x - 1, x * accumulator)
}
factHelper(n, 1)
}
I recommend using some formatter like scalafmt often (e.g. on compile) to spot issues like this immediately. Additionally if you annotated factHelper
as @scala.annotation.tailrec
compiler would fail as this wrong bracket makes it non-tail-recursive, so it would also help spotting the issue.