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

Scala中如何针对不同C类型对象循环调用同一检查函数?

Scala代码风格优化方案

针对你这段重复调用checkFunc的代码,这里提供几种更符合Scala惯用风格的写法:

1. 集合遍历+exists方法(推荐)

把所有C实例放进集合,利用Scala集合的exists方法(和||一样支持短路求值),同时通过部分应用函数固定A、B参数:

def checkFunc(a: A, b: B, c: C): Boolean = {
  a.exists(c.types) && c.contains(b.id)
}

def runner(a: A, b: B): Boolean = {
  // do something
  // if (..) { .... }
  else {
    // 固定a、b参数,得到仅接收C的函数
    val checkWithAB = checkFunc(a, b, _: C)
    // 遍历C实例集合,只要有一个满足就返回true
    List(c1, c2, c3, c4).exists(checkWithAB)
  }
}

2. 简化版集合遍历

可以省略中间变量,直接在集合上编写判断逻辑:

def runner(a: A, b: B): Boolean = {
  // do something
  // if (..) { .... }
  else {
    List(c1, c2, c3, c4).exists(c => checkFunc(a, b, c))
  }
}

3. 函数柯里化改造(可选)

如果checkFunc经常需要固定前两个参数,可以改成柯里化形式,让代码更直观:

// 柯里化后的checkFunc
def checkFunc(a: A, b: B)(c: C): Boolean = {
  a.exists(c.types) && c.contains(b.id)
}

def runner(a: A, b: B): Boolean = {
  // do something
  // if (..) { .... }
  else {
    List(c1, c2, c3, c4).exists(checkFunc(a, b))
  }
}

以上写法都避免了重复的函数调用代码,利用Scala的集合操作和函数式特性,让代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:10:35