Mike_Jr Mike_Jr - 6 months ago 66
Scala Question

Perform more than one operation in scala's foreach?

Let's say I have this ListBuffer that I am filling in a scala foreach like the following:

Tokens.foreach(t => tokens+=new Token(t._1.toString()))


i am wondering whether it is possible to perform another operation at the same time for-example adding to a string something like:

Tokens.foreach(t => tokens+=new Token(t._1.toString()), posTagString+=t._2.toString())


the 2nd example results in a "too many arguments (2) for method foreach" error. Is there a way to do this or shall I just stick too the form of:

for(x<-Tokens){

}

Answer Source

try this? :

Tokens.foreach{t => 
  tokens+=new Token(t._1.toString())
  posTagString+=t._2.toString()
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download