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

Scala测试用例中如何正确访问元组元素以传递参数?

问题解决:Scala元组元素访问错误

报错原因

你写的input[0]、input[1]是错误语法——Scala中二元组(String, String)的元素不能通过方括号索引访问,而是要通过._1(第一个元素)和._2(第二个元素)来获取,或者在模式匹配中直接解构元组。

修复方案

方案1:使用元组原生元素访问语法

把代码里的input[0]替换为input._1,input[1]替换为input._2即可:

test("normal case") {
  val testCases = List(
    ("Andorra", "04") -> (Map("la massana" -> 7211), List("les escaldes"))
  )
  for ((input, (mapOut, listOut)) <- testCases) {
    val computedMap: collection.mutable.Map[String, Int] = PaleBlueDot.cityPopulations(countriesFile, citiesFilename, input._1, input._2)
    val computedList: List[String] = PaleBlueDot.aboveAverageCities(countriesFile, citiesFilename, input._1)
    assert(computedMap == mapOut, s"$input -> $computedMap")
    assert(computedList.sorted == listOut.sorted, s"$input -> $computedList")
  }
}

(顺便将var改为val,符合Scala中变量无需重新赋值时用不可变变量的惯用写法)

方案2:在for循环中直接解构元组

如果觉得input._1不够直观,可以在for循环的模式匹配里直接将元组拆分为具名变量,代码可读性更强:

test("normal case") {
  val testCases = List(
    ("Andorra", "04") -> (Map("la massana" -> 7211), List("les escaldes"))
  )
  for (((country, regionCode), (mapOut, listOut)) <- testCases) {
    val computedMap: collection.mutable.Map[String, Int] = PaleBlueDot.cityPopulations(countriesFile, citiesFilename, country, regionCode)
    val computedList: List[String] = PaleBlueDot.aboveAverageCities(countriesFile, citiesFilename, country)
    assert(computedMap == mapOut, s"($country, $regionCode) -> $computedMap")
    assert(computedList.sorted == listOut.sorted, s"($country, $regionCode) -> $computedList")
  }
}

这里直接把二元组(String, String)拆成了country和regionCode两个变量,逻辑更清晰,也彻底避免了元组元素访问的语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:01:07