Which solution should be generally preferred, considering that the change is source compatible?
This
object Foo {
val Bar = new Baz(42, "The answer", true)
}
or this?
object Foo {
object Bar extends Baz(42, "The answer", true)
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The functional difference between the two constructs is that
object Baris only created when it is needed, whileval Baris created as soon asobject Foois used. As a practical matter, this means you should use the object (orlazy val) if the right-hand side is expensive and won’t always be needed. Otherwise,valis probably simpler.Also, note that if the class
Bazis final, you won’t be able to use theobjectstyle since you can’t extendBaz(though you can still uselazy valif you want to defer creation until it’s needed).