Search code examples
scalascala-2.11

change return type of the superclass method


Having a scala class

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")
    }

I would like to be able to do type of a call

instances.onlyMapReduce.onlySucceeded

where instances is a JobsHistory type. The problem is that I call a filter which is coming from superclass and returns HashSet rather than JobsHistory, how can I ensure proper return type.


Solution

  • I would suggest just adding those methods to a Set using Pimp My Library pattern.

    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))
    

    It would work the same with mutable Set as filter returns a new set no matter if it's mutable or not.