1

Code piece 1

maps foreach { case (k, v) =>
  // do something
}

code piece 2:

maps foreach { 
  case (k, v) => {
    // do something
  }
}

I am new to scala. Just wonder whether the above two pieces of codes are the same or not? which one is better?

Thanks

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
BAE
  • 8,550
  • 22
  • 88
  • 171

1 Answers1

2

Yes, those two pieces of code are same.

But unfortunately none of them takes into account the recommendations of the Scala style guide.

  1. Omitting dots and using spaces is not recommended.

  2. Always omit braces in case clauses.

  3. case may be present on same line or on the next line: it depends on the contents of // do something.

So the original code should be formatted as

maps.foreach {
  case (k, v) => // do something
}
Antot
  • 3,904
  • 1
  • 21
  • 27
  • as for point 3, you mean `case (k, v) =>` and `// do something` may be on the same line? – BAE May 15 '18 at 21:46
  • Yes, everything in this example may be on the same line, if `// do something` is short and concise. – Antot May 15 '18 at 21:51