Wednesday, January 20, 2010

Case classes in 2.8

Thanks to Scala 2.8's default parameters case classes have a couple wonderful new features in Scala 2.8. Specifically the copy method and the ability to have case classes with default parameters.
  1. // constructor methods have defaults defined
  2. scala> case class Node (name:String, left : Option[Node] = None, right : Option[Node] = None)                          
  3. defined class Node
  4. // the name is the only required parameter because it does not have a default
  5. scala> val child = Node("leaf"
  6. child: Node = Node(leaf,None,None)
  7. // left is being assigned here because the name of the parameter is not explicit
  8. scala> val parent = Node("parent", Some(res0))
  9. parent: Node = Node(parent,Some(Node(leaf,None,None)),None)
  10. // now the left node is not defined just the right
  11. scala> val node = Node("node", right=Some(res0))
  12. node: Node = Node(node,None,Some(Node(leaf,None,None)))
  13. /* 
  14. The real power is the copy constructor that is automatically generated in the case class.  I can make a copy with any or all attributes modifed by using the copy constructor and declaring which field to modify
  15. */
  16. scala> parent.copy(right = Some(node))
  17. res4: Node = Node(parent,Some(Node(leaf,None,None)),Some(Node(node,None,Some(Node(leaf,None,None)))))
  18. scala> parent.copy(left=None)         
  19. res5: Node = Node(parent,None,None)
  20. scala> parent.copy(name="hoho")
  21. res6: Node = Node(hoho,Some(Node(leaf,None,None)),None)
  22. scala> parent.copy(name="hoho", left=None)
  23. res7: Node = Node(hoho,None,None)

No comments:

Post a Comment