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

Scala中ZipAll方法的默认填充值是否支持传入动态参数?

实现方案

Scala 标准库原生的zipAll方法仅支持传入静态默认值,无法直接实现动态关联对应位置元素的填充逻辑,不过我们可以通过手动对齐长度再映射的方式轻松实现该需求,完整实现代码如下:

val prices = List(5, 10, 15, 20)
val fruits = List("Guava", "Banana", "Papaya", "Apple", "Mango")

// 取两个列表的最大长度
val maxLen = math.max(fruits.length, prices.length)
// 两个列表都补位到最大长度,缺失位用None标记
val paddedFruits = fruits.map(Some(_)) ++ List.fill(maxLen - fruits.length)(None)
val paddedPrices = prices.map(Some(_)) ++ List.fill(maxLen - prices.length)(None)

val result = paddedFruits.zip(paddedPrices).map {
  case (Some(fruit), Some(price)) => (fruit, price)
  // 价格缺失时,动态拼接当前水果名生成默认值
  case (Some(fruit), None) => (fruit, s"Price Unavailable for $fruit")
  // 水果缺失时返回静态默认值,你也可以按需修改为动态逻辑
  case (None, Some(price)) => ("Undefined Fruit", price)
  case _ => throw new RuntimeException("非法补位结果")
}

运行后输出结果和你期望的完全一致:

List((Guava,5), (Banana,10), (Papaya,15), (Apple,20), (Mango,Price Unavailable for Mango))

如果你的使用场景固定只有fruits列表比prices长,也可以用更简化的写法:

val result = fruits.zip(prices.map(Some(_)).padTo(fruits.length, None)).map {
  case (fruit, Some(price)) => (fruit, price)
  case (fruit, None) => (fruit, s"Price Unavailable for $fruit")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:12:00