Reputation: 13746
I am probably doing something wrong. When I extend a class, I specify the mapping between the extendee's constructor and the extended class constructor:
class Base(one: String, two: String)
case class Extended(one: String, two: String, three: String) extends Base(one, two)
How can I instead suffice with something like any of the following, thus implying a "default" mapping?
class Base(one: String, two: String)
case class Extended(one: String, two: String, three: String) extends Base
class Base(one: String, two: String)
case class Extended(three: String) extends Base
I am probably missing the cleaner way of just adding a parameter without all that ceremony. Or should I be using a trait rather than subclassing, for such simple thing....
Upvotes: 3
Views: 146
Reputation: 3688
All the parameters of a case
class generated apply
method have to be specified in the case
class declaration, so your second proposal cannot work. The first one can be accomplished if Base
is abstract, using abstract val
s:
abstract class Base {
// no initializers!
val one : String
val two : String
def print { println("Base(%s, %s)" format (one, two)) }
}
// Note: constructor arguments of case classes are vals!
case class Extended(one: String, two: String, three: String) extends Base
...
Extended("foo", "bar", "baz").print // prints 'Base(foo, bar)'
However, the names need to match exactly.
Upvotes: 10