更改超类方法的返回类型

时间:2015-10-07 09:54:31

标签: scala scala-2.11

有一个scala类

class JobsHistory extends mutable.HashSet[JobInstance] {

      /**
       * Filter only Map Reduce Jobs
       * @return
       */
      implicit def onlyMapReduce = this.filter((job) => job.mapTasksCount > 0 && job.reduceTasksCount > 0)

      /**
       * Filter only jobs with successful status
       * @return
       */
      implicit def onlySucceeded = this.filter((job) => job.status == "SUCCEEDED")
    }

我希望能够做一个电话类型

instances.onlyMapReduce.onlySucceeded

其中instancesJobsHistory类型。问题是我调用了一个来自超类的过滤器并返回HashSet而不是JobsHistory,我该如何确保正确的返回类型。

2 个答案:

答案 0 :(得分:3)

我建议只使用Pimp My Library模式将这些方法添加到Set

case class JobInstance(status: String, mapTasksCount: Int, reduceTasksCount: Int)

implicit class JobHistory(val jobs: Set[JobInstance]) extends AnyVal {
  def onlyMapReduce = jobs.filter((job) => job.mapTasksCount > 0 && job.reduceTasksCount > 0)

  def onlySucceeded = jobs.filter(_.status == "SUCCEEDED")
}

val set = Set(JobInstance("SUCCEEDED", 3, 3), JobInstance("SUCCEEDED", 0, 3), JobInstance("Failed", 3, 3))

set.onlyMapReduce.onlySucceeded
res3: scala.collection.immutable.Set[JobInstance] = Set(JobInstance(SUCCEEDED,3,3))

对于可变集合,它会起作用,因为filter无论它是否可变都会返回一个新集合。

答案 1 :(得分:2)

我认为这是优先考虑组合而不是继承的好例子。

case class JobHistory(jobs: Set[JobInstance]) {
  def onlyMapReduce = copy(jobs = jobs filter (job => 
    job.mapTasksCount > 0 && job.reduceTasksCount > 0
  ))

  def onlySucceeded = copy(jobs = jobs filter (job => job.status == "SUCCEEDED"))
}

请注意,我已将mutable.HashSet替换为immutable.Set