Scala's sealed abstract vs abstract class

后端 未结 2 1931
自闭症患者
自闭症患者 2021-01-30 10:22

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

相关标签:
2条回答
  • 2021-01-30 10:43

    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.

    0 讨论(0)
  • 2021-01-30 10:55

    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.

    0 讨论(0)
提交回复
热议问题