Lazy Singleton in Scala

As my study of Scala continued, I was intrigued by some of the options in Scala. Consider removing static classes. In the Java world (where I came from), there is a clear distinction between a static element, a single, and an instance member. There was always a constant need for a Java singlet, with which a static member could not really help. The main use cases that I know why a singleton might be preferable to a static member:

  • Ability to manage an instance of a singleton object. If loading an instance of a class is a heavy resource, we want to push it away later until it is really needed.
  • The ability to configure a singleton object at runtime. Imagine you need to read environment variables and populate our singleton at build time. This cannot be done if the element is static, because the information cannot be known at the time the class is loaded.

However, it seems that the implementation of Scala singleton will be deprived of the above advantages. Have a look at the discussion here: http://pbadenski.blogspot.com/2009/06/design-patterns-in-scala-singleton.html

It seems to me that not Scala fully resolves single-user cases. Which will be a disappointment.

If my understanding is correct, then the following question: how to include a lazy singleton pattern in Scala?

Looks like we need to fight Scala to get a plain right track!

PS: This is not my blog.

+4
source share
1 answer

Singles in Scala are lazy. In your REPL, do the following:

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 println, Foo is not initialized until it is used.

+18
source

Source: https://habr.com/ru/post/1495867/


All Articles