【问题标题】:Scala - Superclass instantiate its subclass in its method?Scala - 超类在其方法中实例化其子类?
【发布时间】:2016-02-18 08:16:28
【问题描述】:

我正在 Coursera 上学习“Scala 中的函数式编程原理”课程。在作业 3 中,有一个任务是过滤带有谓词的推文集,并提供了一些结构:

abstract class TweetSet {
  /**
   * This method takes a predicate and returns a subset of all the elements
   * in the original set for which the predicate is true.
   *
   * Question: Can we implment this method here, or should it remain abstract
   * and be implemented in the subclasses?
   */
   def filter(p: Tweet => Boolean): TweetSet = ???

  /**
   * This is a helper method for `filter` that propagetes the accumulated tweets.
   */
   def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet

  /* Some Other Code */

}

class Empty extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = ???
}

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = ???
}

我能够找出抽象类中的filter 方法

def filter(p: Tweet => Boolean, acc: TweetSet): TweetSet = filterAcc(p, new Empty)

这与我在网上可以找到的大多数解决方案相同。

问题是,抽象超类TweetSet 在其方法中实例化其子类Empty 之一。这是一个很好的编程练习吗?它不会破坏类层次结构或抽象的目的吗?

【问题讨论】:

  • 根据您提供的代码,我认为您应该在抽象类中实现filter filterAcc 应该保持抽象,然后实现特定的filterAcc in每个子类。
  • @Łukasz 刚刚纠正了一个错字 - 这正是我在 filter 方法中所做的。但是,如果您查看实现,此方法会调用 new Empty 来实例化其子类 - 但超类不应该知道从它继承的子类。

标签: scala inheritance


【解决方案1】:

它不会破坏类层次结构或抽象的目的吗?

在一般意义上你是对的。但在这种情况下,抽象不会被用作使多个实现成为可能的一种方式,没有EmptyNonEmpty 的 TweetSet 将没有意义。在这种情况下,使用抽象为TweetSet 提供统一接口。

一般的经验法则是,如果它们在同一个文件中,则允许依赖子类型。

【讨论】:

    猜你喜欢
    • 2013-12-15
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多