Scala's sealed abstract vs abstract class

ScalaClassAbstractSealed

Scala Problem Overview


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

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionŁukasz LewView Question on Stackoverflow
Solution 1 - Scalasepp2kView Answer on Stackoverflow
Solution 2 - ScalaDaniel C. SobralView Answer on Stackoverflow