What are the differences between final class and sealed class in Scala?

后端 未结 2 826
囚心锁ツ
囚心锁ツ 2021-01-31 01:45

There are two types of modifiers in Scala: final and sealed

What are the differences between them? When should you use one over the other?

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 02:19

    sealed classes (or traits) can still be inherited in the same source file (where final classes can't be inherited at all).

    Use sealed when you want to restrict the number of subclasses of a base class (see "Algebraic Data Type").

    As one of the very practical benefits of such a restriction the compiler can now warn you about non-exaustive pattern matches:

    sealed trait Duo
    case class One(i:Int) extends Duo
    case class Two(i:Int, j:Int) extends Duo
    
    def test(d:Duo) {
      match {
        case One(x) => println(x) // warning since you are not matching Two
      }
    }
    

提交回复
热议问题