0

I'm relatively new to Scala and am trying to update some of my code but am a little stuck on how to make the best use of Scala's features & syntactic sugar to do what I want.

Here's a simplified example of what I have:

def someFunction(searchItem: String, items: Set[SomeType1]): Set[SomeType2] = 
   items.collect {
      case SomeType1(_, someFieldA, _, importantField1, importantField2, _, someSet)
         if someFieldA == searchItem && importField1 == somethingElse => 
            // do some filtering and mapping
            someSet.filter(x => x.something....)
                   .map { t => SomeType2(.....) }

However I want to be able to add an "else" statement inside the case statement and am having issues:

def someFunction(searchItem: String, items: Set[SomeType1]): Set[SomeType2] = 
   items.collect {
      case SomeType1(_, someFieldA, _, importantField1, importantField2, _, someSet)
         if someFieldA == searchItem && importField1 == somethingElse => 
            // do some filtering and mapping
            someSet.filter(x => x.something....)
                   .map { t => SomeType2(.....) }
         else if someFieldA == somethingElse || someSet.contains("foo") => 
            someSet.filter(x => x.something....)
                   .map { t => SomeType2(.....) }

But it won't compile with that else if in there (it expects a } after .map in the if block...

Is there another way I could do something like this?

CustardBun
  • 3,457
  • 8
  • 39
  • 65
  • 1
    You can add if to your pattern when matching (e.g. https://stackoverflow.com/questions/1585395/using-comparison-operators-in-scalas-pattern-matching-system). Adding another pattern with another if statement would essentially be the same as what you're trying to do. Or just move the if-else-if construct after the =>. – Dennis Hunziker Apr 30 '18 at 22:27

1 Answers1

1

It can't be done in that way because in pattern matching that if is a "guard" condition. No else clause can be added.

Here's the equivalent of what you're after:

def someFunction(searchItem: String, items: Set[SomeType1]): Set[SomeType2] = 
  items.collect {

    case SomeType1(_, someFieldA, _, importantField1, importantField2, _, someSet)
      if someFieldA == searchItem && importField1 == somethingElse => 
            // do some filtering and mapping
            someSet.filter(x => x.something....)
                   .map { t => SomeType2(.....) }

    case SomeType1(_, someFieldA, _, importantField1, importantField2, _, someSet)
      if someFieldA == somethingElse || someSet.contains("foo") => 
            someSet.filter(x => x.something....)
                   .map { t => SomeType2(.....) }
  }

The 2nd case pattern is attempted only if the 1st fails.

jwvh
  • 50,871
  • 7
  • 38
  • 64