本文介绍了使用密封特征和密封抽象类作为基类的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在尝试学习 Akka 的过程中,我经常发现类层次结构与此类似的示例:

While trying to learn Akka, I often find examples with a class hierarchies similar to this:

sealed trait Message

case class TextMessage(user: String, text: String) extends Message
case class StatusMessage(status: String) extends Message

但是,即在 Scala 文档 中有以下示例:

However, i.e. in Scala docs there's a following example:

abstract class Notification

case class Email(sourceEmail: String, title: String, body: String) extends Notification
case class SMS(sourceNumber: String, message: String) extends Notification
case class VoiceRecording(contactName: String, link: String) extends Notification

使用密封特征与抽象类(在本例中为密封抽象类)作为没有构造函数参数的类层次结构的基类有什么区别?使用一种比另一种有什么优势吗?

What's the difference in using a sealed trait vs. an abstract class (or sealed abstract class in this case) as a base class without constructor parameters for a class hierarchy? Are there some advantages in using one over the other?

具体来说,如果特征和抽象类都是密封的,我不能将它们扩展到文件之外,对吗?在那种情况下,我也不能在 Java 中继承它们?如果是这种情况,密封性将呈现 建议的重复项没用,因为它们指的是文件外的继承.

Specifically, if both, the trait and the abstract class are sealed, I can't extend them outside the file, right? In that case I couldn't inherit from them in Java either? If that's the case sealedness would render most of the arguments found in the suggested duplicate useless since they refer to inheritance outside the file.

推荐答案

在这种特殊情况下,除了不能扩展多个 抽象类 但可以扩展多个 之外,没有区别特征.

In this particular case there are no differences except that you can't extend multiple abstract classes but you can extend multiple traits.

您应该检查其他答案(如评论中所述)以查看抽象类和特征之间的实际差异.如果你只是想使用 abstract classtrait 来定义类型层次结构,那么在这种情况下,没有区别.

You should check other answers (as mentioned in the comments) to see the actual differences between abstract classes and traits. If you are just going to use an abstract class or a trait to define the type hierarchy as in this case, then there are no differences.

例如您可以执行以下操作:

E.g. you could to the following:

trait A
trait B

case class C(a: Int) extends A with B

但你不能这样做:

abstract class A
abstract class B

case class C(a: Int) extends A with B

这篇关于使用密封特征和密封抽象类作为基类的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:10