Typical usage:
class Apple private (val color:String) {
// Stuff goes here...
}
object Apple {
def apply(color:String):Apple = new Apple(color)
}
val greenApple = Apple("blue")
val redApple = Apple("white")
One of the main reason to use the companion pattern is to overload the constructors and redefine the behavior of the apply method. This turns very useful when you want to define a factory or when you want to treat an object as a primitive type.
Furthermore, objects serve the same (and some additional) purposes as the static methods and fields in Java.