Initialize internal object just once - scala

In Scala, I have the following class:
class A(param: String) {
object B {
lazy val db = {new D(param)}
}
}
and then from client code I have to create class A objects multiple times but have the B.db parameter be initialized just once. Currently, this does not work as it will create a new instance of object B every time and instance of class A is created.
To add a bit of perspective, the B.db object is an instance of the Mongo class, which according to the documentation needs to be initialized just once. How would you go about it?

put it in a companion object instead of an internal object
object A {
apply(param:String) {
new A
}
lazy val db = {..}
}
class A{
}

Related

How to inject Scala classes in objects?

I want to use a singleton class in a Scala companion object but I am using Guice dependency injection and, as far as I know, it has no explicit usage in these scenarios.
As an example, let's say we have Singleton (using Guice) class as follows:
#Singleton
class Foo Inject()(foo2: Foo2) {
def func = { ... }
}
I can use it in other classes as:
class MyClass Inject()(foo: Foo) {
foo.func()
}
What about objects? I need to create an instance with new as:
object MyObject {
val foo2 = new Foo2()
val foo = new Foo(foo2)
foo.func()
}
In this case, does Foo still have just one instance? I mean, does new Foo(foo2) return the same instance as Guice returns in #Inject()(foo: Foo)?
By the way, there are already questions about this (e.g., link) but I want to use objects and access the singleton instances inside them.
In this case, does Foo still have just one instance? I mean, does new Foo(foo2) return the same instance as Guice returns in #Inject()(foo: Foo)?
No. Just as if you call new Foo(...) elsewhere. My suggestion would just be not to mix it; if you want to use Guice's instances inside MyObject, make it a Guice singleton class as well. Or make Foo an object, you can still access it from Guice-using classes.
If you really need it, the way I can think of is really ugly; to store the Injector from your main (or wherever you create it) somewhere MyObject can access it, i.e.
object Main {
var injector: Injector = null
def main(args: Array[String]): Unit = {
// make sure this happens before MyObject is accessed
injector = Guice.createInjector(...)
...
}
}
object MyObject {
val foo = Main.injector.getInstance(classOf[Foo])
foo.func()
}
If you don't even create the Injector yourself, but are using some framework which uses Guice, check if it gives you access to the Injector.

Dependency Injection on Class Instantiated Elsewhere

I am trying to inject ehcache via the Play Framework. I am injecting it into a companion class, but that class is being instantiated in an abstract class elsewhere as well as the companion object. I do not want to inject anything into the abstract class because it is being used elsewhere.
For example, this is basically how the companion class and object are set up (removed some logic and extensions for better readability):
class Setting #Inject()(cached: DefaultSyncCacheApi) {
def isCached(id:String): Boolean = {
val cachedItem = cached.get(id)
cachedItem.isDefined
}
}
object Setting {
def getId(id:String): Setting = {
val setting = new Setting //I know this doesn't work
if (setting.isCached(id)) {
//retrieval logic
}
setting
}
}
This is the abstract class where it is being instantiated:
abstract class UsingSettingAbstract {
def methodUsingSetting(): String = {
val setting = new Setting
val str = new String
//logic in here
str
}
}
I have tried to create an empty constructor in the Setting class with def this() { }, and creating a chain of constructors, but have so far been unsuccessful in getting the cache to be successfully injected.
I did different versions of below, initializing the cache variable with cached or trying to pass through cached:
class Setting #Inject()(cached: DefaultSyncCacheApi) {
val cache:DefaultSyncCacheApi
def this() {
this(cache)
}
}
Is there a way to get DI to work with this setup, or would something like a factory pattern work better?
With guice you can pass any created instance to the injectors "requestInjection()" method. This will trigger method and field injection on that instance.
So as long as you have access to the injector, you can get injections done.

Run "static call" in object before class instantiation Scala

I want to run some code in the body of an scala companion object before the class is instantiated. The idea is to register a bunch of object in a Set. Here is the code
trait Delegate {
def make: Ins
}
//EDIT: Changed constructor to private
//class Ins
class Ins private()
//this is the companion object that will be registered with the InsDelegate
object Ins extends Delegate{
//here is the code that do the registration but doesn't run
InsDelegate.register(this)
override def make: Ins = {
println("This is an Ins")
new Ins()
}
}
Here is the code for the InsDelegate
object InsDelegate {
private val objectSet = new mutable.HashSet[Delegate]()
def register(obj: Delegate): Unit = objectSet.add(obj)
def getRegisteredObj: Set[Delegate] = objectSet.toSet
}
When I run this test, nothing gets printed.
object test extends App {
InsDelegate.getRegisteredObj.foreach(_.make)
}
The code that register the companion object doesn't run. I know that unlike java, in order to run the companion object code you need to instantiate the class of the object. How do I accomplish what I am trying to do???
Scala objects are lazy, so they're only constructed when first used. In your example, the test application never creates any instances, so object Ins is never constructed.
Your code should work, but you would need to create an instance of class Ins in your test code:
object test extends App {
val temp = Ins.make()
InsDelegate.getRegisteredObj.foreach(_.make)
}
Incidentally, the convention for functions with side-effects (Delegate.make) is to take parentheses; a version without parentheses indicates that the function has no side-effects, which make clearly has (registering the Ins object, creating a new Ins element).
Another Scala convention is to name factory methods apply, rather than make. If you did that, you could create new Ins class instances using Ins(), instead of Ins.make(). (Ins() is interpreted to be the same as Ins.apply().)
Update: Forgot to mention this: if you want to register Ins without creating any instances first, you will need to reference it in some way. This quickly leads to ugly solutions along the lines of:
object Ins extends Delegate{
InsDelegate.register(this)
// Dummy method to get object to register itself.
def register(): Unit = {}
override def make: Ins = {
println("This is an Ins")
new Ins()
}
}
object InsDelegate {
private val objectSet = new mutable.HashSet[Delegate]()
def register(obj: Delegate): Unit = objectSet.add(obj)
def getRegisteredObj: Set[Delegate] = objectSet.toSet
// Create delegate objects...
Ins.register()
}
However, if we're going to go to that much trouble, we might as well forego registration and add objects in the InsDelegate object:
object Ins extends Delegate{
override def make: Ins = {
println("This is an Ins")
new Ins()
}
}
object InsDelegate {
// Set of delegate objects available. Note: this is public, replaces getRegisteredObj.
val objectSet: Set[Delegate] = Set(Ins)
}
The downside is that Delegate objects no longer register themselves, but that's a blessing in disguise as you can now test delegate creation separately from testing InsDelegate.
I know that unlike java, in order to run the companion object code you need to instantiate the class of the object
Actually, your Java code would have the same result. What you need to do in both cases is to load the class, and instantiating it is just one way to do it. You can also use Class.forName, ClassLoader.loadClass, load any class which uses it somewhere in a signature... One very well-known case is (or was, before JDBC 4.0) loading JDBC drivers.
Unfortunately, in Scala the class you need to load is actually Ins$ (the class of the companion object) and instantiating Ins (or loading it in some other way) isn't necessarily enough.

Scala, class using mutable var, update in overriding method

I am having a hard time understanding how to get the following code structure to work.
In Scala I have a class MyClass which inherits from SomeClass I added a var member variable in this case called mutableArray and it is being updated in the overridden method overridingSomeClassMethod and is called when I create a new instance of the MyClass a number of times right away. But in main when I try and get the updated mutableArray variable it prints out the instantiated var as if it is immutable or only has scope in the overriding method.
I can't change the method in parent SomeClass, and I tried creating a companion object as well as putting the variable in the encompassing SomeOtherObject but I get the same exact issue.
import scala.collection.mutable.ArrayBuffer
object SomeOtherObject{
case MyClass(...) extends SomeClass(..){
var mutableArray: ArrayBuffer[Int] = ArrayBuffer.fill(5)(0)
def overridingSomeClassMethod(...){
var someReturnVar = 0.0
mutableArray(0) += 1
println(mutableArray.mkString) // last output -> 84169
someReturnVar
}
}
def main(args: Array[String]){
var mc = new MyClass
println(mc.mutableArray.mkString) // output -> 00000
}
}
You can use an early initializer:
case MyClass(...) extends {
var mutableArray: ArrayBuffer[Int] = ArrayBuffer.fill(5)(0)
} with SomeClass(..) {
Probably you are hitting the infamous "one question FAQ" about initialization order.
If the method is invoked by the superclass constructor, then your initialization happens after that, resetting the data to zero.

Force initialization of Scala singleton object

I'm working on an automatic mapping framework built on top of Dozer. I won't go into specifics as it's not relevant to the question but in general it's supposed to allow easy transformation from class A to class B. I'd like to register the projections from a class's companion object.
Below is a (simplified) example of how I want this to work, and a Specs test that assures that the projection is being registered properly.
Unfortunately, this doesn't work. From what I can gather, this is because nothing initializes the A companion object. And indeed, if I call any method on the A object (like the commented-out hashCode call, the projection is being registered correctly.
My question is - how can I cause the A object to be initialized automatically, as soon as the JVM starts? I don't mind extending a Trait or something, if necessary.
Thanks.
class A {
var data: String = _
}
class B {
var data: String = _
}
object A {
projekt[A].to[B]
}
"dozer projektor" should {
"transform a simple bean" in {
// A.hashCode
val a = new A
a.data = "text"
val b = a.-->[B]
b.data must_== a.data
}
}
Short answer: You can't. Scala objects are lazy, and are not initialized until first reference. You could reference the object, but then you need a way of ensuring the executing code gets executed, reducing the problem back to the original problem.
In ended up doing this:
trait ProjektionAware with DelayedInit
{
private val initCode = new ListBuffer[() => Unit]
override def delayedInit(body: => Unit)
{
initCode += (() => body)
}
def registerProjektions()
{
for (proc <- initCode) proc()
}
}
object A extends ProjektionAware {
projekt[A].to[B]
}
Now I can use a classpath scanning library to initialize all instances of ProjektionAware on application bootstrap. Not ideal, but works for me.
You can force the instantiation of A to involve the companion object by using an apply() method or some other sort of factory method defined in the object instead of directly using the new A() constructor.
This does not cause the object to be initialized when the JVM starts, which I think as noted in another answer can't generally be done.
As Dave Griffith and Don Roby already noted, it cannot be done at JVM startup in general. However maybe this initialization could wait until first use of your framework?
If so, and if you don't mind resorting to fragile reflection tricks, in your --> method you could obtain reference to the companion object and get it initialize itself.
You can start at Getting object instance by string name in scala.
We could use this sort of a way to ensure that companion object gets initialized first and then the class gets instantiated.
object B {
val i = 0
def apply(): B = new B()
}
class B {
// some method that uses i from Object B
def show = println(B.i)
}
// b first references Object B which calls apply()
// then class B is instantiated
val b = B()