Shortcut for subclassing in Scala without repeating constructor arguments?

懵懂的女人 提交于 2019-12-22 03:40:42

问题


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


回答1:


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.




回答2:


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

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

Is this what you are looking for?



来源:https://stackoverflow.com/questions/1653942/shortcut-for-subclassing-in-scala-without-repeating-constructor-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!