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

如何将Scala模式匹配函数中的整数10、15改为可调参数?

解决方案

要把函数里硬编码的10和15改成可调参数,其实很简单,咱们只需要把这两个数值添加到函数的参数列表里,再替换掉模式匹配里的固定值就行。这里我还给参数加了默认值,能保证原来的调用代码不用修改也能正常工作,兼顾兼容性。

修改后的完整函数代码

def replacingElem(
    lines: List[String], 
    last10: String, 
    storeCode: Int = 10,  // 对应原来的硬编码10,设默认值保留原有行为
    replaceCode: Int = 15 // 对应原来的硬编码15,设默认值保留原有行为
): List[String] = {
  if (lines.isEmpty) Nil 
  else {
    val row = lines.head.split("[ \t]+")
    row(0).toInt match {
      case `storeCode` => lines.head :: replacingElem(lines.tail, row(1), storeCode, replaceCode)
      case `replaceCode` => (row(0) + " " + last10 + " " + row(2) + " " + row(3)) :: replacingElem(lines.tail, last10, storeCode, replaceCode)
      case _ => lines.head :: replacingElem(lines.tail, last10, storeCode, replaceCode)
    }
  }
}

关键细节说明

  • 参数新增与默认值:加了storeCode和replaceCode两个参数,默认值设为原来的10和15,这样旧代码直接调用replacingElem(myLines, initVal)依然有效。
  • 模式匹配的参数引用:模式里要用反引号`把参数包起来(比如`storeCode`),因为Scala里模式匹配的变量默认是绑定新值,反引号表示匹配参数本身的数值。
  • 递归传参:递归调用时要把新增的两个参数也传下去,不然递归过程中参数会丢失,逻辑就乱了。

调用示例

  • 沿用原有逻辑(不用传新增参数):
    replacingElem(myLineList, initialLastValue)
    
  • 自定义参数(比如把触发存储的码改成20,触发替换的码改成25):
    replacingElem(myLineList, initialLastValue, 20, 25)
    

如果不需要兼容旧代码,也可以去掉默认值,强制调用时必须传入这两个参数,这样更严谨:

def replacingElem(lines: List[String], last10: String, storeCode: Int, replaceCode: Int): List[String] = {
  // 函数体和上面一致,只是参数无默认值
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:12:38