I need only one instance of a class, so I have to use an object instead of a class. I also need to set some initial value chosen by a client, so I need to a constructor for an object, something like this:
object Object1(val initValue: Int){
//.....
}
I can't use this exact code in Scala. How do I deal with that then?
You have a couple of choices:
Make it a class, have the client construct it, give the value in the parameter
Pro: Preserves immutability
Con: Having only a single instance might be hard to manage
Add a variable for the param to the object, add a setter.
Pro: You still have a singleton
Con: There is mutable state now
Implement a multiton
Pro: Gives you (apparent) immutability and singleton (per param)
Con: More code to implement
You could implement a multiton like this in scala:
class Object1 private (val initValue: Int) {
// ...
}
object Object1 {
val insts = mutable.Map.empty[Int, Object1]
def apply(initV: Int) =
insts.getOrElseUpdate(initV, new Object1(initV))
}
UPDATE You could also turn this into a "singleton with parameter":
object Object1 {
var inst: Option[(Int, Object1)] = None
def apply(initV: Int) = inst match {
case Some((`initV`, i)) => i
case Some(_) =>
sys.error("Object1 already instantiated with different param")
case None =>
val i = new Object1(initV)
inst = Some((initV, i))
i
}
}
The object isn't created until you reference it, so you could do something like the following:
object Test1 extends App {
var x = Console.readLine
println(Object1.initVal)
}
object Object1 {
val initVal:String = Test1.x
}
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