access modifiers - What are the differences between final class and sealed class in Scala? -
there 2 types of modifiers in scala: final
, sealed
what differences between them? when should use 1 on other?
a final
class cannot extended, period.
a sealed
trait can extended in same source file it's declared. useful creating adts (algebraic data types). adt defined sum of derived types.
e.g.:
- an
option[a]
definedsome[a]
+none
. - a
list[a]
defined::
+nil
.
sealed trait option[+a] final case class some[+a] extends option[a] object none extends option[nothing]
because option[a]
sealed, cannot extended other developers - doing alter meaning.
some[a]
final because cannot extended, period.
as added bonus, if trait sealed, compiler can warn if pattern matches not exhaustive enough because knows option
limited some
, none
.
opt match { case some(a) => "hello" }
warning: match may not exhaustive. fail on following input:
none
Comments
Post a Comment