如何在 Scala 中使用 foreach 循环来改变对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7253960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:25:08  来源:igfitidea点击:

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

scalajdbcforeachprepared-statement

提问by Jonas

I use Scala and JDBC, now I want to reuse an PreparedStatementto do a multi-insert. I want to use a foreach-loop over an array, but I can't get it right with Scala.

我使用 Scala 和 JDBC,现在我想重用 anPreparedStatement来做一个多插入。我想在数组上使用 foreach 循环,但我无法在 Scala 中正确使用。

val stmt = conn.prepareStatement(insertStatement)

// wrong Scala
items.foreach(item : MyItem =>
    stmt.setInt(1, item.id)
    stmt.setInt(2, item.value)
    stmt.executeUpdate()
    )

itemsis an array containing multiple MyItem.

items是一个包含多个MyItem.

How can I write this foreach-loop in Scala and reuse the PreparedStatement?

如何在 Scala 中编写这个 foreach 循环并重用PreparedStatement?

回答by Andrzej Doyle

You need to use curly braces for the argument to foreachif you want it to be interpreted as a multi-statement block(which you do).

foreach如果您希望将其解释为多语句(您这样做),则需要使用大括号作为参数。

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

除此之外,你在做什么看起来不错。这是一个 REPL 会话,其中我以类似的方式改变 foreach 块中的对象(为简单起见,使用 StringBuilder):

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

(并且为 foreach 块使用括号会导致错误<console>:3: error: ')' expected but '.' found.

回答by Kevin Wright

A small point, but Andrzej's answer can be cleaned up by using infix notation more liberally:

一个小问题,但 Andrzej 的答案可以通过更自由地使用中缀符号来清理:

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, foreachand filter

一般情况下,它被认为是更地道用于收集操作,如缀形式mapflatMapforeachfilter