Home > Net >  Scala 2.13: avoid repeated case class conversion?
Scala 2.13: avoid repeated case class conversion?

Time:11-14

I have a pattern matching for sealed trait which expects two of one case classes as shown below:

 expressions.head match {
      case SingleValueExpression(value,_operator,_ignoreCase) => filter    FromScala(
        SingleValueExpression(value,_operator,_ignoreCase)
      ).transform(ToJson.string)
      case MultipleValueExpression(value,_operator,_apply,_instances) => filter    FromScala(
        MultipleValueExpression(value,_operator,_apply,_instances)
      ).transform(ToJson.string)
    }

You can see that even after decoding the case classes, I am recreating the case class in the next step:

case MultipleValueExpression(value,_operator,_apply,_instances) => MultipleValueExpression(value,_operator,_apply,_instances)

Is there a way to match the pattern such that I could check if the instance is of that case class and then use the value as it is instead of destructuring it and recreating the same case class?

CodePudding user response:

To just check the type in a pattern match, use :, like so:

expressions.head match {
  case sve: SingleValueExpression => filter    FromScala(sve).transform(ToJson.string)
  case mve: MultipleValueExpression => filter    FromScala(mve).transform(ToJson.string)
}

You could even have something like

val fromScala =
  expressions.head match {
    case sve: SingleValueExpression => FromScala(sve)
    case mve: MultipleValueExpression => FromScala(mve)
  }

filters    fromScala.transform(ToJson.string)

You can alternatively use @ to do extraction and binding in one case (e.g. you want to match based on a component of a case class but save the overall match):

case sve @ SingleValueExpression(value, _, _) if somePredicate(value) =>
  // sve is the overall SingleValueExpression, and value is also available in this branch
  • Related