抽象类中辅助构造函数的用例是什么?

发布于 2024-12-02 06:53:42 字数 223 浏览 0 评论 0原文

考虑这段代码:

abstract class Foo(val s: String) {
  def this(i: Int) = this("" + (i+2))
}

据我了解,构造函数不是继承的,并且不能像 Java 中那样使用 super 从子类调用辅助构造函数。

它们只是一个无用的工件还是这个结构有一些合理的用例?

Consider this code:

abstract class Foo(val s: String) {
  def this(i: Int) = this("" + (i+2))
}

As far as I understand constructors aren't inherited and secondary constructors cannot be called from subclasses with super like in Java.

Are they just a useless artifact or is there some sensible use-case for this construct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

初吻给了烟 2024-12-09 06:53:42
scala> object Bar extends Foo(3)
defined module Bar

scala> Bar.s
res3: String = 5
scala> object Bar extends Foo(3)
defined module Bar

scala> Bar.s
res3: String = 5
帥小哥 2024-12-09 06:53:42

子类的主构造函数必须调用超类的构造函数之一,但不一定是主类的构造函数。

abstract class A(s: String) {
  def this(i: Int) = this(i.toString)
}
class B(i: Int) extends A(i)

The primary constructor of the subclass must call one of the constructor of the superclass, not necessarily the primary one.

abstract class A(s: String) {
  def this(i: Int) = this(i.toString)
}
class B(i: Int) extends A(i)
迷途知返 2024-12-09 06:53:42

除了@coubeatczech的答案之外,如果添加细化,您还可以创建抽象类(和特征)的实例,

scala> :paste
// Entering paste mode (ctrl-D to finish)

abstract class Foo(val s: String) {
  def this(i: Int) = this("" + (i+2))
}

// Exiting paste mode, now interpreting.

defined class Foo

scala> val f = new Foo(23) {}
f: Foo = $anon$1@13d874e

scala> f.s
res3: String = 25

尽管我在上面显示了一个空的细化(“{}”),但您通常会提供一些额外的定义,通常提供抽象成员的实现,

scala> abstract class Bar { def bar : Int }
defined trait Bar

scala> val b : Bar = new Bar { def bar = 23 }
b: Bar = $anon$1@1e17c6d

scala> b.bar
res1: Int = 23

In addition to @coubeatczech's answer, you can also create instances of abstract classes (and traits) if you add a refinement,

scala> :paste
// Entering paste mode (ctrl-D to finish)

abstract class Foo(val s: String) {
  def this(i: Int) = this("" + (i+2))
}

// Exiting paste mode, now interpreting.

defined class Foo

scala> val f = new Foo(23) {}
f: Foo = $anon$1@13d874e

scala> f.s
res3: String = 25

Although I've show an empty refinement above ("{}") you would typically provide some additional definitions, often providing implementations for abstract members,

scala> abstract class Bar { def bar : Int }
defined trait Bar

scala> val b : Bar = new Bar { def bar = 23 }
b: Bar = $anon$1@1e17c6d

scala> b.bar
res1: Int = 23
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文