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] defined some[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

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -