实现一个不仅仅设置变量的Scala构造函数

Ste*_*ins 15 java scala

大多数情况下,类的构造函数只会获取其参数值并使用它们来设置实例变量:

// Java
public class MyClass {
   private int id;

   public MyClass(int id) {
      this.id = id;
   }
}
Run Code Online (Sandbox Code Playgroud)

所以我理解了Scala默认构造函数语法的效率......只需在类名旁边的括号中声明一个变量列表:

// Scala
class MyClass(id: int) {
}
Run Code Online (Sandbox Code Playgroud)

但是,除了简单地将参数插入实例变量之外,那些需要构造函数实际执行STUFF的情况呢?

// Java
public class MyClass {
   private String JDBC_URL = null;
   private String JDBC_USER = null;
   private String JDBC_PASSWORD = null;

   public MyClass(String propertiesFilename) {
      // Open a properties file, parse it, and use it to set instance variables.
      // Log an error if the properties file is missing or can't be parsed.
      // ...
   }
}
Run Code Online (Sandbox Code Playgroud)

这在Scala中如何工作?我可以尝试为这个构造函数定义一个实现,如下所示:

// Scala
class MyClass(propertiesFilename: String) {
  def this(propertiesFilename: String) {
    // parse the file, etc
  }
}
Run Code Online (Sandbox Code Playgroud)

...但是我收到编译错误,抱怨构造函数定义了两次.

我可以通过使用no-arg默认构造函数来避免这种冲突,然后将上面声明为重载的辅助构造函数.但是,你真正需要"一对一"构造函数的情况怎么样,你需要它做什么呢?

Dir*_*irk 23

您只需在类体中执行这些操作即可.

Class Foo(filename: String) {
    val index =  {
         val stream = openFile(filename)
         readLines(stream)
         ...
         someValue
     }
     println(“initialized...“) 
}
Run Code Online (Sandbox Code Playgroud)


Did*_*ont 5

您放在类主体中的任何代码都在构造时执行

class MyClass(propertiesFileName: String) {
  println("Just created an instance of MyClass with properties in " + propertiesFileName)
  val myFavoriteProperty = retrieveFavoriteFrom(propertiesFileName)
}
Run Code Online (Sandbox Code Playgroud)

这可能有点尴尬,将成员声明和初始化代码交错过来肯定不是一个好主意,但为了方便变量初始化语法付出的代价很小.