Scala 的密封抽象与抽象类

发布于 2024-09-05 23:56:34 字数 55 浏览 2 评论 0原文

密封抽象抽象 Scala 类有什么区别?

What is the difference between sealed abstract and abstract Scala class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

治碍 2024-09-12 23:56:34

不同之处在于密封类的所有子类(无论是否抽象)必须与密封类位于同一文件中。

The difference is that all subclasses of a sealed class (whether it's abstract or not) must be in the same file as the sealed class.

携余温的黄昏 2024-09-12 23:56:34

正如回答,所有直接继承密封类的子类(无论是否抽象)必须位于同一文件中。这样做的一个实际结果是,如果模式匹配不完整,编译器会发出警告。例如:

sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[T](value: T) extends Tree
case object Empty extends Tree

def dps(t: Tree): Unit = t match {
  case Node(left, right) => dps(left); dps(right)
  case Leaf(x) => println("Leaf "+x)
  // case Empty => println("Empty") // Compiler warns here
}

如果 Treesealed,那么编译器会发出警告,除非最后一行未被注释。

As answered, all directly inheriting subclasses of a sealed class (abstract or not) must be in the same file. A practical consequence of this is that the compiler can warn if the pattern match is incomplete. For instance:

sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[T](value: T) extends Tree
case object Empty extends Tree

def dps(t: Tree): Unit = t match {
  case Node(left, right) => dps(left); dps(right)
  case Leaf(x) => println("Leaf "+x)
  // case Empty => println("Empty") // Compiler warns here
}

If the Tree is sealed, then the compiler warns unless that last line is uncommented.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文