Unit 而不是 Int 的类型不匹配错误(Scala)

Type mismatch error of Unit instead of Int (Scala)

我是 Scala 的新手,我正在尝试像这样定义尾递归阶乘函数:

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

但是它给了我一个不匹配的错误,说它找到了一个 Unit 类型而不是一个 Int 并且我不知道如何,我检查了其他具有相同错误的 Scala 问题(比如这个: ) 但我似乎没有犯这些错误。

这是错误信息:

type mismatch;
 found   : Unit
 required: Int
  }

错误的括号。你有:

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

而不是

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

我建议经常使用 scalafmt 之类的格式化程序(例如在编译时)以立即发现此类问题。此外,如果您将 factHelper 注释为 @scala.annotation.tailrec 编译器将失败,因为这个错误的括号使其成为非尾递归,因此它也有助于发现问题。