【发布时间】: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应该保持抽象,然后实现特定的filterAccin每个子类。 -
@Łukasz 刚刚纠正了一个错字 - 这正是我在
filter方法中所做的。但是,如果您查看实现,此方法会调用new Empty来实例化其子类 - 但超类不应该知道从它继承的子类。
标签: scala inheritance