Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a foreach-loop in Scala that mutates an object?

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?

like image 616
Jonas Avatar asked Aug 31 '11 07:08

Jonas


2 Answers

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.)

like image 158
Andrzej Doyle Avatar answered Nov 09 '22 08:11

Andrzej Doyle


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

like image 24
Kevin Wright Avatar answered Nov 09 '22 07:11

Kevin Wright