Scala列表元素求和问题:优雅实现行内第二、第三元素相加
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, andnum2Strmakes 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
addIntfunction—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

