I use Scala and JDBC, now I want to reuse an PreparedStatement to do a multi-insert. I want to use a foreach-loop over an array, but I can't get it right with Scala.
val stmt = conn.prepareStatement(insertStatement)
// wrong Scala
items.foreach(item : MyItem =>
stmt.setInt(1, item.id)
stmt.setInt(2, item.value)
stmt.executeUpdate()
)
items is an array containing multiple MyItem.
How can I write this foreach-loop in Scala and reuse the PreparedStatement?
You need to use curly braces for the argument to foreach if you want it to be interpreted as a multi-statement block (which you do).
Asides from that, what you're doing looks fine. Here's a REPL session where I'm mutating an object in a foreach block in a similar way (using a StringBuilder for simplicity):
scala> val sb = new java.lang.StringBuilder
sb: java.lang.StringBuilder =
scala> val items = List("tinker", "tailor", "soldier", "spy")
items: List[java.lang.String] = List(tinker, tailor, soldier, spy)
scala> items.foreach { item =>
| sb.append(item)
| sb.append("; ")
| println(sb)
| }
tinker;
tinker; tailor;
tinker; tailor; soldier;
tinker; tailor; soldier; spy;
(And using parentheses for the foreach block leads to the error <console>:3: error: ')' expected but '.' found.)
A small point, but Andrzej's answer can be cleaned up by using infix notation more liberally:
val sb = new java.lang.StringBuilder
val items = List("tinker", "tailor", "soldier", "spy")
items foreach { item =>
sb append item
sb append "; "
println(sb)
}
Generally, it's considered more idiomatic to use the infix form for collection operations such as map, flatMap, foreach and filter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With