代码之家  ›  专栏  ›  技术社区  ›  Łukasz Lew

Scala的密封抽象与抽象类

  •  62
  • Łukasz Lew  · 技术社区  · 16 年前

    两者有什么区别 sealed abstract abstract Scala类?

    2 回复  |  直到 11 年前
        1
  •  90
  •   sepp2k    16 年前

    不同之处在于,密封类的所有子类(无论是否抽象)都必须与密封类位于同一个文件中。

        2
  •  77
  •   Community Mohan Dere    9 年前

    作为 answered ,全部 直接继承 密封类的子类(抽象或非抽象)必须在同一个文件中。这样做的一个实际结果是,如果模式匹配不完整,编译器可以发出警告。例如:

    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
    }
    

    Tree sealed ,则编译器会发出警告,除非最后一行未注释。

    推荐文章