Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how would I give a Singleton a constructor?

My design incorporates a small database abstraction, whereby I implement each database as a Singleton (well, an object), with custom methods on the database for the couple of operations the code calls (it's mainly a log parser, dumping interesting statistics to a database).

I'd like to construct the Singleton database classes if possible, such that at runtime, each is constructed with config values (and those values remain constant for the remainder of the program's runtime). This would allow me to better test the code too (as I can mock the databases using Mockito or some such).

I'm still only learning Scala, but it seems there's no way to attach a constructor to a Singleton, and would appreciate any input on this problem - is there a better way to do what I'm doing? Is there some preferred way of constructing a Singleton?

Cheers in advance for any help.

like image 778
frio Avatar asked Jun 27 '10 23:06

frio


2 Answers

Just put the constructor code in the body of the object definition:

object Foo {
    println("Hello") // This will print hello the first time
                     // the Foo object is accessed (and only
                     // that once).
}
like image 91
sepp2k Avatar answered Oct 13 '22 01:10

sepp2k


Rather than use a singleton (which is hard to test).. Whoever's creating the actors could create a database session factory and pass it to each actor, then it's still shared... and testable.

like image 28
Nigel Thorne Avatar answered Oct 12 '22 23:10

Nigel Thorne