Monday, September 14, 2009

Factory Methods and Companion Objects

One of the most common uses of a companion object (See Companion Objects for more) is as a factory for creating instances of the class. For example, there may be several overloaded apply methods which provide different ways of instantiating the object. This is often preferred to adding many constructors because Scala places restrictions on constructors that Java does not have.

One built in example of Factory methods in a companion object are when you create a case class.

  1. scala> caseclass Data(p1:Int, p2:String)
  2. defined class Data
  3. // This is using the generated (or synthetic) factory method.
  4. // call case classes have a factory method generated
  5. scala> Data(1,"one")
  6. res0: Data = Data(1,one)
  7. // This is the normal new syntax.
  8. // case-classes are normal object so they have one of these too
  9. scala> new Data(1,"one")
  10. res1: Data = Data(1,one)
  11. scala> class MyClass(val p1:Int, val p2:String)
  12. defined class MyClass
  13. // MyClass is a normal class so there is no
  14. // synthetic factory method
  15. scala> MyClass(1,"one")
  16. :5: error: not found: value MyClass
  17.        MyClass(1,"one")
  18.        ^
  19. // but of course you can create an instance normally
  20. scala> new MyClass(1,"one")
  21. res3: MyClass = MyClass@55444319
  22. // create the companion object with an apply factory method
  23. scala> object MyClass{
  24.      | def apply(p1:Int, p2:String)=new MyClass(p1,p2)
  25.      | }
  26. defined module MyClass
  27. // now you can create MyClass as if it was a case-class
  28. // It is not a case-class so you still don't have the other
  29. // synthetic methods like: equals, hash-code, toString, etc...
  30. scala> MyClass(1,"one")
  31. res4: MyClass = MyClass@2c5e5c15

No comments:

Post a Comment