在 Scala 中,如何将具有多个构造函数的 Java 类子类化? [英] In Scala, how can I subclass a Java class with multiple constructors?

查看:24
本文介绍了在 Scala 中,如何将具有多个构造函数的 Java 类子类化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有多个构造函数的 Java 类:

Suppose I have a Java class with multiple constructors:

class Base {
    Base(int arg1) {...};
    Base(String arg2) {...};
    Base(double arg3) {...};
}

如何在 Scala 中扩展它并仍然提供对 Base 的所有三个构造函数的访问?在 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 may not themselves have constructor parameters, but you can work around that by using abstract members instead.

这篇关于在 Scala 中,如何将具有多个构造函数的 Java 类子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆