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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With