As my learning of Scala continues, I have been intrigued by some of the choices in the Scala language. Consider the removal of static classes. In Java world (from where I come), there is a distinct difference between a static member, a singleton and a instance member. There was always a persistent need for a singleton in Java which a static member could not really help with. The primary use cases I know for why a singleton may be preferred over a static member are:
It appears however that Scala's implementation of singleton will be devoid of the above benefits. Look at the discussion here: http://pbadenski.blogspot.com/2009/06/design-patterns-in-scala-singleton.html
It appears to me that does not Scala solve the singleton use cases at all. Which would be a disappointment.
If my understanding is correct then the next question is: How do we enable a lazy singleton pattern in Scala?
Seems like we have to fight scala to get singleton the correct way!
PS: This is not my blog
Singletons in Scala are lazy. Try the following in your REPL:
scala> object Foo { println("hello") }
defined module Foo
scala> 1+1
res0: Int = 2
scala> Foo
hello
res1: Foo.type = Foo$@37c8ccf4
scala> Foo
res2: Foo.type = Foo$@37c8ccf4
As you can see from the println, Foo isn't initialized until it's used.
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