如果禁止case类继承,如何表示? [英] If case class inheritance is prohibited, how to represent this?

查看:48
本文介绍了如果禁止case类继承,如何表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建案例类,如 这篇文章

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

但是,我在 IntelliJ 中收到以下错误.我理解为什么它被禁止(为什么要逐案继承在 Scala 中是禁止的).这里的替代方法是什么?

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
           ^

推荐答案

Exp 不应使用 case 关键字.也就是说,密封的抽象案例类很少(如果有的话)使用起来有意义.

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

在这种特定情况下,您从 密封抽象案例类 Exp() 获得的唯一额外东西是一个自动生成的伴随对象 Exp,它具有一个 取消应用 方法.而这个 unapply 方法不会很有用,因为没有任何东西可以从通用的 Exp 中提取.也就是说,你只关心分解AddSub

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.

这很好:

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

这篇关于如果禁止case类继承,如何表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆