【问题标题】:Is it ok for a child class to convert a concrete method back to abstract?子类可以将具体方法转换回抽象方法吗?
【发布时间】:2014-04-21 17:07:58
【问题描述】:

在 scala 中(或者一般来说)是否可以有一个具体的实现,然后再强制转换为更抽象的方法?例如

trait Tree {
  def print(s:String) = println(s)
}

trait Leaf extends Tree {

  def print(s:String) // force use of this to be defined later. Maybe I need the word override?

}

这个人为的例子展示了我以前从未真正考虑过使用的东西,即开始具体但扩展抽象。实际上,我已经构建了一个树状类结构,它可以处理大部分具体代码,直到它遇到各种叶类,此时我不想意外忘记覆盖。

【问题讨论】:

    标签: scala


    【解决方案1】:

    您不能“取消实现”一个方法。使用您的示例,可以定义

    class Foo extends Leaf
    

    没有任何对编译器的抱怨,这意味着从你的 Tree trait 派生的所有类都已经实现了 print 方法。

    您可以提供一个默认实现,但仍然通过使用两个特征来确保您不会在任何地方使用它

    trait Tree {
      def method() // abstract method
    }
    
    trait DefaultImpl {
      def method() = {
        // default implementation
      } 
    }
    
    // now you can do things like
    
    class Foo extends Tree with DefaultImpl // this will use the default implementation
    
    class Bar extends Tree // this will not compile until you provide an implementation for method
    

    【讨论】:

    • 谢谢,我没有想到 2 个特征是解决方案
    • 如果希望强制具体类改变实现怎么办?更准确地说,我希望创建一个 trait 'ClassWithReasonableToStringMethod'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多