本文介绍了实现一个不仅仅是设置变量的 Scala 构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Most of the time, a constructor for a class does nothing more than take its argument values and use them to set instance variables:

// Java
public class MyClass {
   private int id;

   public MyClass(int id) {
      this.id = id;
   }
}

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

So I understand the efficiency of Scala's default constructor syntax... simply declaring a list of variables in parentheses beside the class name:

// Scala
class MyClass(id: int) {
}

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

However, what about those circumstances where you need a constructor to actually DO STUFF, apart from simply plugging arguments into instance variables?

// 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.
      // ...
   }
}

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

How does this work in Scala? I can try to define an implementation for this constructor like so:

// Scala
class MyClass(propertiesFilename: String) {
  def this(propertiesFilename: String) {
    // parse the file, etc
  }
}

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

... but I get a compilation error, complaining that the constructor is defined twice.

我可以通过使用无参数默认构造函数,然后将上面的内容声明为重载的辅助构造函数来避免这种冲突.但是,如果您确实需要一个且唯一一个"的构造函数,并且您需要它来做事,那该怎么办?

I could avoid this conflict by having a no-arg default constructor, and then declaring the above as an overloaded secondary constructor. However, what about situations in which you really DO need "one-and-only-one" constructor, and you need it to do stuff?

推荐答案

您可以简单地在类主体中执行这些操作.

You can perform these actions simply in the class body.

Class Foo(filename: String) {
    val index =  {
         val stream = openFile(filename)
         readLines(stream)
         ...
         someValue
     }
     println("initialized...")
}

这篇关于实现一个不仅仅是设置变量的 Scala 构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:43