Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a constructor for an 'object' class type in Scala? I.e., a one time operation for the singleton

Tags:

I know that objects are treated pretty much like singletons in scala. However, I have been unable to find an elegant way to specify default behavior on initial instantiation. I can accomplish this by just putting code into the body of the object declaration but this seems overly hacky. Using an apply doesn't really work because it can be called multiple times and doesn't really make sense for this use case.

Any ideas on how to do this?

like image 980
Zack Avatar asked Mar 04 '11 23:03

Zack


People also ask

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.

Does object have a constructor in Scala?

Constructors in Scala describe special methods used to initialize objects. When an object of that class needs to be created, it calls the constructor of the class. It can be used to set initial or default values for object attributes.


1 Answers

Classes and objects both run the code in their body upon instantiation, by design. Why is this "hacky"? It's how the language is supposed to work. If you like extra braces, you can always use them (and they'll keep local variables from being preserved and world-viewable).

object Initialized {   // Initalization block   {     val someStrings = List("A","Be","Sea")     someStrings.filter(_.contains('e')).foreach(s => println("Contains e: " + s))   }    def doSomething { println("I was initialized before you saw this.") } }  scala> Initialized.doSomething Contains e: Be Contains e: Sea I was initialized before you saw this.  scala> Initialized.someStrings <console>:9: error: value someStrings is not a member of object Initialized        Initialized.someStrings 
like image 187
Rex Kerr Avatar answered Oct 23 '22 23:10

Rex Kerr