Search code examples
scalavariadic-functionsvariable-length

how to implement variable length argument function in scala


I have to concatenate k different lengths of strings into one string res and save res string into ArrayBuffer[String]().
But the k is variable.
For example,

val result = new ArrayBuffer[String]()
result.+=("1\t" + A.toString() + "\t" + ls.pid + "\t" + ls.did + "\t" + ls.sid + "\t" + ls.request_time.substring(0,10))

result.+=("2\t" + B.toString() + "\t" + ls.pid + "\t" + ls.did + "\t" + ls.sid + "\t")

result.+=("2\t" + B.toString() + "\t" + ls.pid + "\t" + ls.did + "\t")

result.+=("2\t" + B.toString() + "\t")

How to use a function with a variable-length argument to implement it?

Thanks in advance.


Solution

  • You can use the following syntax:

    def f(args: String*) = {
        args.map{s =>
        //todo: process single item
        s
      }
    }