如果返回Unit,则Scala递归函数else

时间:2018-02-20 06:19:56

标签: scala tail-recursion

Noob Scala问题:

我有以下代码摘录:

@tailrec
def buildObjectFromFile(dataList: List[String], fileObject: IncomingFile): IncomingFile = {
  dataList match {
    case Nil => fileObject

    case data :: list =>
      val recordIdentifier = data.substring(0, 2)

      if (recordIdentifier.equals("00")) {
        val fileHeader = new fFileHeader(
            ...
        )

        buildObjectFromFile(list, new IncomingFile(fileHeader, fileObject.accountsList, fileObject.fileTrailer))
      } else if (recordIdentifier.equals("01")) {
        val accountHeader = new AccountHeader(
          ...
        )

        fileObject.accountsList += new Account(data.substring(12, 22), accountHeader, null, null, null)

        buildObjectFromFile(list, new IncomingFile(fileObject.fileHeader, fileObject.accountsList, fileObject.fileTrailer))
      } else if (recordIdentifier.equals("99")) {  // <--- Problematic
        val fileTrailer = new FileTrailer(
          ...
        )

        buildObjectFromFile(list, new IncomingFile(fileObject.fileHeader, fileObject.accountsList, fileTrailer))
      }
  }
}

此代码无法编译,因为编译器抱怨最后一个else if块返回Unit,而需要返回IncomingFile类型。我不明白为什么只有最后一个if语句有问题。

1 个答案:

答案 0 :(得分:2)

您可以通过为整个if-else-if表达式实现else来解决。现在你没有它所以整个块都有单元类型