【发布时间】:2015-12-10 19:39:52
【问题描述】:
假设我在树结构中有一个复杂的节点层次结构,其中某些类型的节点只能具有某些(可能很多,甚至可能包括它自己的类型)类型的子节点。
假设我们有一棵员工树,并且想要编码哪些类型的员工可以成为老板,哪些其他类型。
一种方法是定义我们的Employee 类型President、CTO、Manager,以及它们对应的“下属”类型PresidentSubordinate、CTOSubordinate、ManagerSubordinate。然后,您可以将*Subordinate 扩展到他们可以成为老板的任何Employee。然后你可以这样做:
sealed trait Employee
sealed trait PresidentSubordinate extends Employee
sealed trait VicePresidentSubordinate extends Employee
sealed trait CTOSubordinate extends Employee
sealed trait ManagerSubordinate extends Employee
sealed trait DeveloperSubordinate extends Employee
case class President(subordinates: Seq[PresidentSubordinate])
case class VicePresident(subordinates: Seq[VicePresidentSubordinates])
extends PresidentSubordinate
case class CTO(subordinates: Seq[CTOSubordinate])
extends PresidentSubordinate
with VicePresidentSubordinate
case class Manager(subordinates: Seq[ManagerSubordinate])
extends VicePresidentSubordinate
case class Developer(subordinates: Seq[DeveloperSubordinate])
extends CTOSubordinate
with ManagerSubordinate
with VicePresidentSubordinate
with DeveloperSubordinate // Devs can be bosses of other devs
// Note, not all employees have subordinates, no need for corresponding type
case class DeveloperIntern()
extends ManagerSubordinate
with DeveloperSubordinate
这种方法对我的六种左右的树节点类型效果很好,但我不知道这是否是最好的方法,因为类型的数量增加到 10 或 50 种类型。也许有一个更简单的解决方案,可能适合使用here 所示的模式。类似的东西
class VicePresidentSubordinate[T <: Employee]
object VicePresidentSubordinate {
implicit object CTOWitness extends VicePresidentSubordinate[CTO]
implicit object ManagerWitness extends VicePresidentSubordinate[Manager]
implicit object DeveloperWitness extends VicePresidentSubordinate[Developer]
}
但是我不确定生成的案例类会是什么样子,因为这显然无法编译:
case class VicePresident(subordinates: Seq[VicePresidentSubordinate]) extends Employee
感谢您的帮助!
【问题讨论】:
-
我遇到过这种情况。它从类型系统的 POV 中运行良好,但是是的,您会获得许多人为的超级特征。也许这在 Dotty 中使用联合类型变得更简单......
-
是的!我等不及要联合类型了 :)
标签: scala hierarchy hierarchical-data