【问题标题】:Scala: to inherit abstract methodsScala:继承抽象方法
【发布时间】:2012-11-17 11:01:58
【问题描述】:

我有一个这样的类层次结构。

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 上放置一个抽象方法“验证”,以供我的所有类继承。并且只在具体实施。 我该怎么做呢? 我的验证方法必须有不同的签名 有些返回一个值,但有些则不返回任何内容。

例如,我想要这样的东西:

 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
}

【问题讨论】:

    标签: scala methods abstract inheritance


    【解决方案1】:

    这是无法做到的。重写的方法需要具有兼容的签名。这意味着相同数量的参数,在 args 中是逆变的,在返回中是协变的。这意味着您的 args 可以是被覆盖的 args 的超类型,并且返回类型可以是被覆盖的返回类型的子类型,但它们不能任意变化。

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

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 1970-01-01
      • 2013-07-01
      • 2012-08-06
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 2012-04-25
      相关资源
      最近更新 更多