Can case class inheritance be used when matching patterns in Scala 2.10.0?

I could not find the answer to this simple question, maybe I used the wrong keywords for the search.

To create an AST, I need nodes like Number, Add, Sub, Mul, Div, etc. Since many mathematical operations have the same structure, how can I handle all of them within the same template? For instance. the lines below are not said to be syntactically correct:

object AST { sealed abstract class Expr case class MathOp(e1: Expr, e2: Expr) extends Expr case class Number extends Expr case class Add(e1: Expr, e2: Expr) extends MathOp(e1, e2) case class Sub(e1: Expr, e2: Expr) extends MathOp(e1, e2) } 

The goal is to do:

 expr match { case MathOp(e1: Expr, e2: Expr) => //do something that would be done to Add, Sub, Mul, Div case Number => //do another thing } 
+4
source share
2 answers
Class classes

do much more than adding extractors based on patterns, for example. they add equality, a product iterator and arity, etc., and so the odd things happen under inheritance. Therefore, case class inheritance was deprecated before and is now impossible in Scala 2.10.

For your case, you need a custom extractor ( unapply method):

 object AST { sealed trait Expr object MathOp { def unapply(m: MathOp): Option[(Expr, Expr)] = Some(m.e1 -> m.e2) } sealed trait MathOp extends Expr { def e1: Expr def e2: Expr } case class Number extends Expr case class Add(e1: Expr, e2: Expr) extends MathOp case class Sub(e1: Expr, e2: Expr) extends MathOp } 

Question related to us

+5
source

As far as I understand this problem, I have no reason to use "case classes" for children. We hope that the correct code is as follows:

 object AST { sealed abstract class Expr case class MathOp(e1: Expr, e2: Expr) extends Expr case class Number extends Expr class Add(e1: Expr, e2: Expr) extends MathOp(e1, e2) class Sub(e1: Expr, e2: Expr) extends MathOp(e1, e2) } expr match { case MathOp(e1: Expr, e2: Expr) => //do something that would be done to Add, Sub, Mul, Div case Number => //do another thing } 
0
source

Source: https://habr.com/ru/post/1487004/


All Articles