拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Unit而不是Int(Scala)的型别不匹配错误

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

白鹭 - 2022-02-10 1996 0 0

我是 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 问题有同样的错误(比如这个:Scala Type Mismatch Unit 而不是 Int)但没有似乎我没有犯这些错误。

这是错误讯息:

type mismatch;
 found   : Unit
 required: Int
  }

uj5u.com热心网友回复:

错误的括号。你有:

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编译器将失败,因为这个错误的括号使其非尾递回,因此它也有助于发现问题。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *