Saturday, December 26, 2009

Product

As a response to a comment on a previous post about about Tuples this topic is about Products and the most common subclasses of Tuples.

I should preface this post by saying that I am not going to attempt any scholastic style discussions, instead I am going to try to explain Product in practical terms and stay away from theory. That said on can think of Products as (potentially) heterogenous collections (non-resizable collections). There are several Product classes (Product, Product1, Product2...). All Product classes extend Product, which contains the common methods. Product has the methods for accessing the Product members and the subclass adds type information about the Members.

A good way to think about Product is to look at Tuple which is a Product. There is a good stack overflow question that is worth looking at.

To give more context consider other well known subclasses of Product:
  • All case classes
  • List
  • Option

  1. scala> val product : Product = (1,'2',3)
  2. product: Product = (1,2,3)
  3. scala> product.productIterator.foreach {println _}
  4. 1
  5. 2
  6. 3
  7. scala> product.productArity                       
  8. res1: Int = 3
  9. scala> product.productElement(2)
  10. res2: Any = 3
  11. scala> product.productPrefix    
  12. res3: java.lang.String = Tuple3
  13. scala> product.toString
  14. res4: java.lang.String = (1,2,3)
  15. scala> val product3 = product.asInstanceOf[Product3[Int,Char,Int]]
  16. product3: Product3[Int,Char,Int] = (1,2,3)
  17. scala> product3._2
  18. res5: Char = 2
  19. scala> product3._3
  20. res6: Int = 3
  21. scala> case class Test(name:String, passed:Boolean, error:String)
  22. defined class Test
  23. scala> Test("Chicken Little"false"the sky is falling")
  24. res7: Test = Test(Chicken Little,false,the sky is falling)
  25. scala> res7.productArity
  26. res8: Int = 3
  27. scala> res7.productIterator mkString ", "   
  28. res9: String = Chicken Little, false, the sky is falling

No comments:

Post a Comment