samidarko samidarko - 26 days ago 7
Scala Question

Scala inheritance : how to pass a parameter to parameter without declaring it in child?

I would like to initialise a parent object that needs a parameter but without declaring in child constructor

class A(name: String)


What I see everywhere is

class B(name: String) extends A(name)


but what I would like to do is

class B extends A {
def this() = this("valueOfName") // string "valueOfName" is passed to A
}


Is it possible to do this in Scala?

** EDIT **

This is just a toy example, my real case is more complex, but I want to transform the parameter passed to the parent:

class B(other: String) extends A {
def this() = this(other ++"valueOfName")
}

Answer

Just pass the value directly to the constructor of A. Like this:

class B extends A("valueOfName")