Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for subclassing in Scala without repeating constructor arguments?

Let's say I have some classes like this:

abstract class View(val writer: XMLStreamWriter) {
    // Implementation
}

class TestView(writer: XMLStreamWriter) extends View(writer) {
    // Implementation
}

Most subclasses of View are not going to take different constructor arguments. I would like to be able to write something like this:

class TestView extends View {
    // Implementation
}

Is there some shortcut to write subclasses so that you don't have to explicitly define the constructor args and pass them to the superclass (so that I don't have to re-write all my subclasses if I change the signature of the superclass)?

like image 563
Daniel Worthington Avatar asked Oct 31 '09 10:10

Daniel Worthington


2 Answers

I'm afraid you're on your own there. Constructors aren't inherited or polymorphic and subclass constructors, while they must and always do invoke a constructor for their immediate superclass, do not and cannot have that done automatically, except if there's a zero-arg constructor, which is implied by the mention of the superclass's name in an "extends" clause.

like image 75
Randall Schulz Avatar answered Sep 30 '22 19:09

Randall Schulz


abstract class View {
    def writer: XMLStreamWriter
    // Implementation
}

class TestView(val writer: XMLStreamWriter) extends View {
    // Implementation
}

Is this what you are looking for?

like image 20
Mushtaq Ahmed Avatar answered Sep 30 '22 20:09

Mushtaq Ahmed