scala中的构造函数(主要/辅助/默认主要) [英] constructors in scala (primary/auxiliary/default primary)

查看:252
本文介绍了scala中的构造函数(主要/辅助/默认主要)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Cay Horstmann的 的一个很简单的练习让我感到困惑。它是关于 primary 辅助默认主要构造函数: / p>

A quite simple exercise from Cay Horstmann's book « Scala for the impatient » keeps puzzling me. It's about primary,auxiliary and default primary constructors :


ex 5.10:
考虑类



class Employee(val name: String, var salary: Double) {
  def this() { this("John Q. Public", 0.0) }
}




显式字段和默认主构造函数。

Rewrite it to use explicit fields and a default primary constructor.

我不知道我应该做什么。你可能有人提出一个解决方案?

I'm not sure about I am supposed to do. Could some of you propose a solution ?

但是,试图解决这个练习可能让我意识到一些我没有注意到的主要构造函数和 val 字段(如您所见,我不太确定):

However, trying to solve this exercise may have made me aware of something I hadn't noticed before about primary constructor and val fields (as you can see, I'm not quite sure) :

code> val 字段(如 Employee 类中的 name )只能通过构造函数而不是辅助初始化?在后一种情况下,编译器会将其视为对 val 字段的重新赋值,从而导致错误。

Am I right if I say that a val field (as name in the Employee class above) may only be initialized through the primary constructor and not by an auxiliary one ? In the latter case it would be considered by the compiler as a reassignment to a val field causing an error.

起初,我认为 val 字段大致相当于java中的final字段,希望它是合法的在任何构造函数中第一次赋值它们,但似乎我错了。

At first I thought to val fields as a rough equivalent to final fields in java expecting that it would be legal to assign them for the first time in any constructor but it seems I was wrong.

我不太满意什么可能只是一个野生的猜测,所以我会欣赏如果有人可以给我更准确的信息。

I am not quite satisfied with what may only be a wild guess so I would appreciate if someone could give me more accurate information about that point.

推荐答案

从Programming in Scala,第2版第6.7节:

From "Programming in Scala, 2nd edition" paragraph 6.7:

在Scala中,每个辅助构造函数必须调用与其第一个动作相同类的另一个构造函数。
这个规则的净效果是,Scala中的每个构造函数调用都将最终调用该类的主构造函数。因此,主要构造函数是类的单个入口点。

In Scala, every auxiliary constructor must invoke another constructor of the same class as its first action. The net effect of this rule is that every constructor invocation in Scala will end up eventually calling the primary constructor of the class. The primary constructor is thus the single point of entry of a class.

所有用于初始化 val的数据

So all data for initialization of val must be in primary constructor.

您的具有显式字段的类可能是这样的:

Your class with explicit fields may be something like:

class Employee(n: String = "John Q. Public", s: Double = 0.0) {
  val name = n
  var salary = s
}

或没有默认参数值:

class Employee(n: String, s: Double) {
  def this() = this("John Q. Public", 0.0)
  val name = n
  var salary = s
}

这篇关于scala中的构造函数(主要/辅助/默认主要)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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