在Scala中,我如何使用多个构造函数来子类化一个Java类? [英] In Scala, how can I subclass a Java class with multiple constructors?
问题描述
假设我有一个具有多个构造函数的Java类:
Suppose I have a Java class with multiple constructors:
class Base {
Base(int arg1) {...};
Base(String arg2) {...};
Base(double arg3) {...};
}
我如何在Scala中扩展它,构造函数?在Scala中,子类只能调用它的超类的构造函数之一。
How can I extend it in Scala and still provide access to all three of Base's constructors? In Scala, a subclass can only call one of it's superclass's constructors. How can I work around this rule?
假设Java类是我不能改变的旧代码。
Assume the Java class is legacy code that I can't change.
推荐答案
很容易忘记一个trait可能会扩展一个类。如果你使用trait,你可以推迟哪个构造函数调用的决定,例如:
It's easy to forget that a trait may extend a class. If you use a trait, you can postpone the decision of which constructor to call, like this:
trait Extended extends Base {
...
}
object Extended {
def apply(arg1: Int) = new Base(arg1) with Extended
def apply(arg2: String) = new Base(arg2) with Extended
def apply(arg3: Double) = new Base(arg3) with Extended
}
Traits自身可能没有构造函数参数,但你可以使用抽象成员来解决这个问题。
Traits may not themselves have constructor parameters, but you can work around that by using abstract members instead.
这篇关于在Scala中,我如何使用多个构造函数来子类化一个Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!