4

I'm splitting a long string into an array of strings, then I want to insert all of them to the database. I can easily loop through the array and insert one by one, but it seems very inefficient. Then I think there is a insertAll() method. However, the insertAll() method is defined like this:

def insertAll(values: U*)

This only accepts multiple U, but not an Array or List.

/* Insert a new Tag  */
def insert(insertTags: Array[String])(implicit s: Session) {
  var insertSeq: List[Tag] = List()
  for(tag <- insertTags) {
    insertSeq ++= new Tag(None, tag)
  }
  Tag.insertAll(insertSeq)

}

*Tag is the table Object

This is the preliminary code I have written. It doesn't work because insertAll() doesn't take Seq. I hope there is a way to do this...so it won't generate an array length times SQL insertion clause.

1 Answer 1

6

When a function expect repeated parameters such as U* and you want to pass a sequence of U instead, it must be marked as a sequence argument, which is done with : _* as in

Tag.insertAll(insertSeq: _*)

This is described in the specification in section 6.6. It disambiguates some situations such as ;

def f(x: Any*)
f(Seq(1, "a"))

There, f could be called with a single argument, Seq(1, "a") or two, 1 and "a". It will be the former, the latter is done with f(Seq(1, "a"): _*). Python has a similar syntax.


Regarding the questions in your comment : It works with Seq, collections that confoms to Seq, and values that can be implicitly converted to Seqs (which includes Arrays). This means a lot of collections, but not all of them. For instances, Set are not allowed (but they have a toSeq methods so it is still easy to call with a Set).

It is not a method, it it more like a type abscription. It simply tells the compiler that this the argument is the full expected Seq in itself, and not the only item in a sequence argument.

Sign up to request clarification or add additional context in comments.

2 Comments

Does this : _* sequence argument marker only apply to Seq or does it apply to some other collections as well? How does : _* this work if you don't mind me asking? Is it a method? A built in iteration of sort?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.