Scala Slick Bulk Insert with Array

scala, slick

Solution

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.

Problem

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.

Original source

Related problems