Search code examples
scalafunctional-programmingreturn-current-type

Scala: Maintain child class in parent methods?


When you have a parent:

abstract class Parent {
   def something(arg: ???): Parent = ???
}

and

class Child extends Parent {}

I would like

val updatedChild = new Child().something(...)

updatedChild to be of type Child and not of type Parent, is it possible ?


Solution

  • One way to do it, is to parametrize the parent:

     abstract class Parent[T <: Parent[T]] {
        def something(arg: Foo): T
     }
    
     class Child(val foo: String) extends Parent[Child] {
        def something(arg: String) = return new Child(arg)
     }
    

    Sometimes, you can also get away with using this.type:

    class Parent {
      def something(arg: Foo): this.type = this
    }
    class Child {
       override def something(arg: Foo) = this
    }
    

    But the latter method only works if all you ever want to return is this (this.type is not Parent or Child, but a specific type that only has one instance - this).