Search code examples
scalafunction-literal

scala: whether the following two are the same


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


Solution

  • 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
    }