How do I initialize object vals with values known only at runtime?

You could employ the use of lazy vals. This may make things more complex any you still need to use a var.

You could employ the use of lazy vals. This may make things more complex any you still need to use a var. Case class Config( height: Int, width: Int ) object Field { val defaultConfig = Config( 20, 15 ) var config: OptionConfig = None def getConfig = config.

GetOrElse( defaultConfig ) lazy val height = getConfig. Height lazy val width = getConfig. Width } object Main extends App { Field.

Config = Some( Config( 30, 25 ) ) }.

I think, I get the idea. Thanks! – Saptamus Prime Jan 9 at 0:08.

Case class Field(width: Int, height: Int) { //... } object Main { def main(args: ArrayString): Unit = { val field = Field(30, 25) } }.

Because it's not elegant. Objects must be introduced in Scala for a reason. Or else, why would people use objects at all?

– Saptamus Prime 2 days ago 3 @Saptamus Only because the singleton pattern is called a design pattern doesn't mean it's elegant and you should use it. I'm using objects and I would not use them for your use case. – ziggystar 2 days ago 2 Using class is definitely de way to go.

@SaptamusPrime Not sure why you say it's not elegant. The situation you describe is a standard use case in OO architecture. You are trying to force the use of Object in a situation where it does not fit.

Objects are meant to be used as companions for a class, to hold the stuff common to all instances like the static part of a class in Java. That's why they're called "companion objects". – Cristian Vrabie 2 days ago 1 @SaptamusPrime: Looks perfectly elegant to me.

– missingfaktor 2 days ago 1 @SaptamusPrime "Elegance is a synonym for beauty that has come to acquire the additional connotations of unusual effectiveness and simplicity" - Wikipedia. Using a class is elegant if anything, especially in comparison to the accepted answer. Scala code needn't to be overengineered, in fact it can be very simple and elegant, neither singleton design pattern nor lazy initialisation fits here.

– Vlad Gudim 2 days ago.

One option is lazy vals: object Field { lazy val height = // code to find height lazy val width = // code to find width } The val will be initialised the first time it's used, so as long as you don't use them until you have all the information you need to initialise them, you should be good.

But that's still doesn't provide the way to set this fields from the outside – om-nom-nom Jan 9 at 0:07.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions