如何在Scala中实现变长参数函数并用于可变数量字符串拼接存入ArrayBuffer
Hey there! Let's break down how to solve this problem using Scala's variable-length parameter functions. It's actually pretty straightforward once you know the syntax, and it'll clean up your code a lot.
Step 1: Define a variable-length parameter function for string concatenation
In Scala, you can create a function that accepts any number of arguments by adding an * after the parameter type. This turns the parameter into a Seq inside the function, which we can easily join with tabs using mkString.
Here's the function:
def concatWithTabs(parts: String*): String = parts.mkString("\t")
This function takes any number of String arguments, joins them with tab characters (\t), and returns the resulting string—perfect for your use case!
Step 2: Use this function to populate your ArrayBuffer
Now, instead of manually concatenating each string with + and tabs, you can pass all the parts directly to concatWithTabs and add the result to your ArrayBuffer. Let's rewrite your example code using this function:
First, make sure you import ArrayBuffer:
import scala.collection.mutable.ArrayBuffer
Then, create your buffer and populate it:
val result = new ArrayBuffer[String]() // First entry: 6 parts, no trailing tab result += concatWithTabs( "1", A.toString, ls.pid.toString, ls.did.toString, ls.sid.toString, ls.request_time.substring(0, 10) ) // Second entry: 5 parts plus an empty string to add a trailing tab result += concatWithTabs( "2", B.toString, ls.pid.toString, ls.did.toString, ls.sid.toString, "" ) // Third entry: 4 parts plus an empty string result += concatWithTabs( "2", B.toString, ls.pid.toString, ls.did.toString, "" ) // Fourth entry: 2 parts plus an empty string result += concatWithTabs( "2", B.toString, "" )
Notice that to get the trailing tab in your later entries, we just add an empty string as the last argument—mkString will add a tab before this empty string, resulting in the trailing tab you need.
Bonus: Wrap it up in a helper function (optional)
If you want to make it even cleaner, you can create a helper function that both concatenates and adds to the buffer in one step:
def addToBuffer(buffer: ArrayBuffer[String], parts: String*): Unit = { buffer += concatWithTabs(parts: _*) }
Then you can call it like this:
addToBuffer(result, "1", A.toString, ls.pid.toString, ls.did.toString, ls.sid.toString, ls.request_time.substring(0,10)) addToBuffer(result, "2", B.toString, ls.pid.toString, ls.did.toString, ls.sid.toString, "") // And so on...
The parts: _* syntax tells Scala to treat the variable-length parameter as a sequence when passing it to concatWithTabs.
That's it! This approach makes your code more readable and maintainable, especially if you have more entries to add later.
内容的提问来源于stack exchange,提问作者Bowen Peng

