In most cases I use the companion object's apply
method, because the code looks less cluttered. However, there is at least one benefit of using a static factory. Consider the unimaginative type MyInt
which just wraps an Int
:
class MyInt(val i: Int)
I can obtain instances of MyInt
calling the constructor which will instantiate a new object each time the constructor is called. If my program relies heavy on MyInt
this results in a lot of instances created. Assuming most of the MyInt
I use are -1
, 0
, and 1
, since MyInt
is immutable I can reuse the same instances:
class MyInt(val i: Int)
object MyInt {
val one = new MyInt(1)
val zero = new MyInt(0)
val minusOne = new MyInt(-1)
def apply(i: Int) = i match {
case -1 => minusOne
case 0 => zero
case 1 => one
case _ => new MyInt(i)
}
}
So at least for immutable values there can be a technical advantage of using the static factory over calling the constructor. As an implication, if you want to express in code that a new instance is created, then use the new
keyword. Personally, I use the new
-keyword when creating objects, and the apply
-method when creating values, though I don't know if there is an official convention.
new
is like wearing a top hat or suspenders. It's stylish for a certain style, but not very contemporary. The companion factory is a pair of casual fit jeans. – Imitative