Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Singleton in Scala

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:

  1. Ability to control the instantiation of an singleton object. If loading the instance of a class is resource heavy, we want to push it off for later till it is actually needed.
  2. Ability to configure a singleton object at runtime. Imagine having to read environment variables and populate our singleton at construction time. This cannot be done if the member is static since the information may not be known at class loading time.

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

like image 996
vecktorking Avatar asked Nov 29 '22 01:11

vecktorking


1 Answers

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.

like image 85
ethzero Avatar answered Dec 05 '22 09:12

ethzero