You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala递归函数if语句返回Unit与List[Entry]类型不匹配如何解决

错误触发原因

Scala 中代码块的返回值为块内最后一个表达式的求值结果,你的代码存在两处返回值不符合预期的问题:

  • 内层 if (index == lines.size - 1) 的 else 分支最后一个语句是变量定义:val Data = pRecurrsioon(lines, index + 1) ++ FBData.toList,变量定义语句的求值结果为 Unit 类型,而非你期望的 List 类型。
  • 外层 if (tmpList.size == 14) 没有对应的 else 分支,当 tmpList 长度不等于14时,整个条件块没有显式返回值,默认返回 Unit,和函数声明的返回值 List[HelloWorld.Entry] 不匹配。

修复方案

修改后代码如下:

if (tmpList.size == 14) {
    val FBData =  Entry (tmpList(0), tmpList(1),tmpList(2),tmpList(3),tmpList(4),tmpList(5).toInt,tmpList(6).toInt,tmpList(7).toInt,tmpList(8).toInt,tmpList(9).toInt,tmpList(10).toInt,tmpList(11).toInt,tmpList(12).toInt,tmpList(13).toInt)
    if (index == lines.size - 1) {
        List(FBData)
    } else {
        // 移除变量定义,直接返回表达式结果
        pRecurrsioon(lines, index + 1) ++ FBData.toList
    }
} else {
    // 补充else分支的返回逻辑,可根据业务场景调整,示例返回空列表
    List.empty[Entry]
}

如果业务逻辑可以保证 tmpList 长度一定为14,也可以在else分支抛出异常避免静默失败:

} else {
    throw new RuntimeException(s"非法的tmpList长度:${tmpList.size}")
}

内容的提问来源于stack exchange,提问作者Armature

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 00:30:01