Scala:继承抽象方法

时间:2012-11-29 11:21:47

标签: scala methods abstract inheritance

我有这样的类层次结构。

abstract class Element {
  var name: String
  var description: String 
}

class Group (var name : String, var description : String, var members: Set[Element] =Set()) 
extends Element{}

trait TypedElement extends Element{ 
  var types: Set[Type] 
}

trait ArchitecturalElement extends PropertyHolderElement with TypedElement

abstract class Component extends ConnectableElement with ArchitecturalElement {
  var subElements : Set[ArchitecturalElement]
 var interactionPoints : Set[InteractionPoint]
}

class SAComponent ( var name :String,
                var description : String,

                var types : Set[Type] = Set(),
                var subElements : Set[ArchitecturalElement] = Set(),
                var interactionPoints : Set[InteractionPoint] = Set()
                ) extends Component

Element是我模型的根类。 现在我想在Element上添加一个抽象方法“validate”,以便我的所有类继承。并且仅在具体实施。 我该怎么做呢? 我验证的方法必须具有不同的签名 有些人返回一个值,但其他人不会返回任何内容。

例如,我想要这样的事情:

 abstract class Element {
  var name: String
  var description: String 
  def validate (elem: Element)
}

class Group (var name : String, var description : String, var members: Set[Element] =Set()) 
extends Element{
validate (gr: Group) = {//the method body}
}

trait TypedElement extends Element{ 
  var types: Set[Type] 
  validate (ty : TypedElement )
}

trait ArchitecturalElement extends PropertyHolderElement with TypedElement {
validate (arel: ArchitecturalElement )
}

abstract class Component extends ConnectableElement with ArchitecturalElement {
  var subElements : Set[ArchitecturalElement]
 var interactionPoints : Set[InteractionPoint]
 validate (el : Component, subElem: Set[ArchitecturalElement]) : Boolean = {//the method body}
 //here, I need the return value to avoid cycles of recursion
}

1 个答案:

答案 0 :(得分:0)

这不可能。重写的方法需要具有兼容的签名。这意味着相同数量的参数,args中的逆变,返回中的协变。这意味着你的args可以是被重写的args的超类型,返回类型可以是被重写的返回类型的子类型,但它们不能任意改变。

现在你可以违反这些规则,但是你不会覆盖,只是重载,你仍然需要提供抽象方法的实现。