Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a single Scala constructor that does more than set variables

Tags:

java

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;
   }
}

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) {
}

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

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?

like image 625
Steve Perkins Avatar asked Jun 16 '11 17:06

Steve Perkins


People also ask

What is constructor overloading in Scala?

A scala class can contain zero or more auxiliary constructors. The auxiliary constructor in Scala is used for constructor overloading and defined as a method using this name. The auxiliary constructor must call either previously defined auxiliary constructors or primary constructors in the first line of its body.

How do we define an auxiliary constructor?

Auxiliary constructors are defined by creating methods named this . Each auxiliary constructor must begin with a call to a previously defined constructor. Each constructor must have a different signature. One constructor calls another constructor with the name this .

What is constructor explain different types of constructor in Scala?

Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.

How do I create a class constructor in Scala?

In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.


2 Answers

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...“) 
}
like image 72
Dirk Avatar answered Oct 20 '22 04:10

Dirk


Any code you put in the body of the class is executed at construction

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

It may be a little awkward and it is certainly not a good idea to interleave your member declaration and your initialization code a lot, but it is a small price to pay for the the convenience of the variable initialization syntax

like image 31
Didier Dupont Avatar answered Oct 20 '22 03:10

Didier Dupont