The difference between using a sealed trait and a private abstract class as a base class

When trying to learn Akka, I often find examples with class hierarchies like this:

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

However, for example, in Scala docs there is the 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 is the difference in using a closed attribute versus an abstract class (or a closed abstract class in this case) as a base class without constructor parameters for the class hierarchy? Are there any advantages to using one over the other?

Edit:

In particular, if both the trait and the abstract class are sealed, I cannot distribute them outside the file, right? In this case, I also could not inherit them in Java? If this closure of the case makes most of the arguments found in the proposed duplicate useless, as they relate to inheritance outside the file.

+5
source share
1 answer

There are no differences in this particular case, except that you cannot extend multiple abstract classes , but you can extend multiple traits .

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

eg. You can:

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

but you cannot do:

 abstract class A abstract class B case class C(a: Int) extends A with B 
+6
source

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


All Articles