简体   繁体   English

如何使用多个操作初始化一个字段?

[英]How to initialize a field with more than one operation?

class A (names: String*) {
  val namesBuffer: ListBuffer[String] = new ListBuffer[String]
}

I was wondering, how I can add the names of the names array from the primary constructor argument to the namesBuffer field when creating the object ? 我想知道,在创建对象时,如何将主构造函数参数中的名称数组的名称添加到namesBuffer字段中? Do I have to create an auxiliary construtor to do so or is there another way to tell Scala to do operations in the primary Constructor ? 我是否必须创建一个辅助构造器来执行此操作,还是有另一种方法告诉Scala在主构造函数中执行操作?

Note: The example above is fictive, I just want to know, how I can tell the primary constructor to do some more operations than assigning fields. 注意:上面的示例是虚构的,我只想知道,我如何告诉主构造函数执行比分配字段更多的操作。

Every statement in the body of the class definition becomes a part of the body of the default constructor. 类定义主体中的每个语句都成为默认构造函数主体的一部分。

In your example you can just do: 在您的示例中,您可以执行以下操作:

class A (names: String*) {
  val namesBuffer: ListBuffer[String] = new ListBuffer[String]
  namesBuffer ++= names
}

or shorter: 或更短:

class A (names: String*) {
  val namesBuffer: ListBuffer[String] = new ListBuffer[String] ++= names
}

or: 要么:

class A (names: String*) {
  val namesBuffer: ListBuffer[String] = ListBuffer[String](names: _*)
}

As axel22's answer demonstrates, you can perform those operations anywhere in the body of the class. 正如axel22的答案所展示的,您可以在类主体中的任何位置执行那些操作。

But it is good practice IMO to initialize the field fully with a single expression. 但是,IMO的优良作法是使用单个表达式完全初始化该字段。

When side effects are required, you can achieve this using curly braces to make a block, which is an expression having the value of the last line: 当需要副作用时,可以使用大括号制作一个块来实现此目的,该块是具有最后一行值的表达式:

class A(names: String*) {
  val namesBuffer: ListBuffer[String] = {
    val buffer = new ListBuffer[String]
    buffer ++= names
    buffer
  }
}

With this technique, you ensure that no other initialization logic accesses the value of namesBuffer before you have finished initializing that. 使用此技术,可以确保在完成初始化之前,没有其他初始化逻辑可以访问namesBuffer的值。

In Scala the entire class definition is effectively the default constructor, if that makes sense. 在Scala中,整个类定义实际上是默认的构造函数,如果可以的话。

You can do something like this: 您可以执行以下操作:

class A (names: String*) {
  val namesBuffer: ListBuffer[String] = new ListBuffer[String]
  namesBuffer.add(names)
}

You could also initialize the names buffer if it took a string array: 您也可以初始化名称缓冲区(如果它使用了字符串数组):

class A (names: String*) {
  val namesBuffer: ListBuffer[String] = new ListBuffer[String](names)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM