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

Scala FlattenArray扁平化列表单元测试失败问题求助

解决Scala扁平化数组时过滤null的问题

你的测试失败核心原因就是没有过滤输入中的null值——原代码会把null当成普通元素保留在结果里,虽然Nil的处理是正确的(不会向结果中添加内容),但null是独立的元素类型,需要额外判断排除。

咱们来修改你的实现:

object FlattenArray {
  def flatten(list: List[Any]): List[Any] = {
    list match {
      case Nil => Nil
      // 遇到嵌套列表,递归扁平化后和剩余部分的结果拼接
      case (x: List[Any]) :: tail => flatten(x) ::: flatten(tail)
      // 遇到null直接跳过,不加入结果,继续处理剩余元素
      case null :: tail => flatten(tail)
      // 非null的普通元素,加入结果后继续处理剩余部分
      case x :: tail => x :: flatten(tail)
    }
  }
}

改动说明:

  • 新增case null :: tail分支:当列表头部是null时,直接跳过这个元素,递归处理剩余的tail部分,不会把null混入最终结果。
  • 其余分支逻辑保持不变:嵌套列表继续递归扁平化,非null的普通元素正常加入结果,空列表返回Nil。

现在运行你的测试用例:

FlattenArray.flatten( List(0, 2, List(List(2, 3), 8, List(List(100)), null, List(List(null))), -2))

会返回List(0, 2, 2, 3, 8, 100, -2),完全符合预期。

如果你想让代码更贴合Scala的惯用写法,也可以用flatMap简化实现,逻辑是一样的:

object FlattenArray {
  def flatten(list: List[Any]): List[Any] = list.flatMap {
    case xs: List[Any] => flatten(xs)
    case null => Nil
    case x => List(x)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:56:09