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
相关产品推荐
相关产品推荐

