Val or object for an immutable final singleton object

Which solution should be generally preferred given that the change is compatible with the source code?

it

object Foo { val Bar = new Baz(42, "The answer", true) } 

or that?

 object Foo { object Bar extends Baz(42, "The answer", true) } 
+7
source share
2 answers

The functional difference between the two constructs is that the object Bar is created only when necessary, and the val Bar is created as soon as the object Foo . As a practical matter, this means that you should use an object (or lazy val ) if the right side is expensive and not always necessary. Otherwise val is probably simpler.

Also note that if the Baz class is final, you cannot use the object style since you cannot extend Baz (although you can still use lazy val if you want to defer creation until you need it).

+8
source

I say the first, because in the second, you create a new class, but you do not add any information (without overriding methods, values ​​or new ones).

+2
source

All Articles