Pattern matching for nested List with additional size constraints
    Swaranga Sarma 
    sarma.swaranga at gmail.com
       
    Mon Jan 25 22:58:59 UTC 2021
    
    
  
Hello, I was going through some code in my work today and came across
several similar looking cases and was wondering if pattern matching would
be a more concise and cleaner way to pxress the logic.
Here is a succinct class hierarchy that illustrates the example:
class Profile {
  Rules rules;
}
class Rules {
  List<Rule> ruleList;
}
class Rule {
  DynamicConfig dynamicConfig;
  StaticConfig staticConfig;
}
class DynamicConfig {
  SomeProperty property;
}
class StaticConfig {
  SomeOtherProperty property;
}
With the above classes, we have a method "isDynamicConfigProfile" that
determines if the Profile is a DynamicConfig profile. A Profile is
considered dynamic if it contains a Rule with a non-null DynamicConfig
member; also ALL the Rules of a profile can only contain one type either
Dynamic or Static so checking just the first element in the ruleList is
sufficient.
The current code is implemented as:
boolean isDynamicProfile (Profile profile) {
  return profile.rules() != null &&
             profile.rules().ruleList() != null &&
             profile.rules().ruleList().size() > 0 &&
             profile.rules().rulesList().get(0).dynamicConfig() != null;
}
Is the above method something that could be expressed with a switch and
pattern matching; assuming these are converted to Record classes? Something
like:
boolean isDynamicProfile (Profile profile) {
  return switch(profile) {
    case Profile(Rules(Rule(DynamicConfig dc), Rule(var r2)...
remainingElements)) -> true;
    default-> false;
  }
}
Is it even a valid usage of patterns? I think even the List interface would
need to support pattern matching in this case.
Regards
Swaranga
    
    
More information about the amber-dev
mailing list