Scala's sealed abstract vs abstract class

*爱你&永不变心* 提交于 2019-12-31 08:10:56

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3032771/scalas-sealed-abstract-vs-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!