Home > Software engineering >  scala: preferred way of using map function
scala: preferred way of using map function

Time:05-20

I prefer to apply map on a list as:

items.map( myItem => ...)

But I also see many examples as:

items.map { case MyItem(...) => ... }

So which one is idiomatic?

CodePudding user response:

Both are perfectly fine. The second one is just a convenient syntax sugar for

items.map { myItem =>
  myItem match {
    case MyItem(...) => ...
  }
}

If you don't need to do a match on myItem, then the first syntax is what you'd generally use.

  • Related