开发者

val or object for immutable, final singleton object

开发者 https://www.devze.com 2023-03-08 02:45 出处:网络
Whi开发者_StackOverflow中文版ch solution should be generally preferred, considering that the change is source compatible?

Whi开发者_StackOverflow中文版ch 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)
}


The functional difference between the two constructs is that object Bar is only created when it is needed, while val Bar is created as soon as object Foo is used. As a practical matter, this means you should use the object (or lazy val) if the right-hand side is expensive and won't always be needed. Otherwise, val is probably simpler.

Also, note that if the class Baz is final, you won't be able to use the object style since you can't extend Baz (though you can still use lazy val if you want to defer creation until it's needed).


I say the first since in the second, you are creating a new class but don't add any information (no overriding of methods, values or new ones).

0

精彩评论

暂无评论...
验证码 换一张
取 消