Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 283
Wonay Avatar asked Dec 30 '25 02:12

Wonay


1 Answers

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

like image 52
Dima Avatar answered Jan 01 '26 18:01

Dima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!