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

Scala列表元素求和问题:优雅实现行内第二、第三元素相加

Solution to Append Sum of Numbers in List Strings

First, let's figure out why your current code is giving that strange output: when you do e + " " + ..., e is the array returned by split("\\s+"). Calling toString on an array in Scala doesn't join its elements—it returns an internal identifier like [Ljava.lang.String;@..., which is why you're seeing those odd prefixes instead of the original fruit names and numbers.

Here's a clean, elegant way to get your desired result, using pattern matching for readability and clarity:

val listin = List("banana 20 20", "apple 50 20", "berry 10 10")

val listout = listin.map { line =>
  // Split the line into parts, handling any number of whitespace characters
  line.split("\\s+") match {
    // Destructure the array into meaningful variables
    case Array(name, num1Str, num2Str) =>
      // Calculate the sum of the two numbers
      val sum = num1Str.toInt + num2Str.toInt
      // Build the output string with all original parts plus the sum
      s"$name $num1Str $num2Str $sum"
  }
}

Result:

listout: List[String] = List(banana 20 20 40, apple 50 20 70, berry 10 10 20)

Key Improvements:

  • Pattern Matching: Destructuring the split array directly into name, num1Str, and num2Str makes the code intuitive and easy to follow.
  • String Interpolation: Scala's s"..." syntax lets you build the output string cleanly without messy concatenation.
  • Conciseness: We don't need a separate addInt function—simple addition can be done inline here for brevity.

Optional: Handling Invalid Lines

If you want to avoid runtime errors from malformed lines (like those with non-integer values or missing parts), use flatMap with Option to skip invalid entries:

val listout = listin.flatMap { line =>
  line.split("\\s+") match {
    case Array(name, num1Str, num2Str) =>
      try {
        val sum = num1Str.toInt + num2Str.toInt
        Some(s"$name $num1Str $num2Str $sum")
      } catch {
        case _: NumberFormatException => None // Skip lines with non-numeric values
      }
    case _ => None // Skip lines with too few/many parts
  }
}

This version will gracefully ignore any lines that don't match your expected format.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:07:38