Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

scala - If case class inheritance is prohibited, how to represent this?

I am trying to create the case classes as explained in this article

sealed abstract case class Exp()
case class Literal(x:Int) extends Exp
case class Add(a:Exp, b:Exp) extends Exp
case class Sub(a:Exp,b:Exp) extends Exp

However, I am getting the following error in IntelliJ. I understand why it is prohibited (Why case-to-case inheritance is prohibited in Scala). What is the alternate way here?

Error:(2, 13) case class Literal has case ancestor A$A34.A$A34.Exp, but case-to-case inheritance is prohibited. To overcome this limitation, use extractors to pattern match on non-leaf nodes.
case class Literal(x:Int) extends Exp
           ^
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Exp shouldn't use the case keyword. That is, a sealed abstract case class will rarely, if ever, make sense to use.

In this specific case, the only extra thing you get from sealed abstract case class Exp() is an auto-generated companion object Exp that has an unapply method. And this unapply method won't be very useful, because there isn't anything to extract from the generic Exp. That is, you only care about decomposing Add, Sub, etc.

This is just fine:

sealed abstract class Exp

case class Literal(x: Int) extends Exp

case class Add(a: Exp, b: Exp) extends Exp

case class Sub(a: Exp, b: Exp) extends Exp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...