Sunday, August 9, 2009

Case classes

Case classes are a special type of class that comes with several convenient definitions (equals, hashCode, toString, copy). There are two main uses:

1. Data object
2. Matching

First examples is using as a datastructure (Note: Some and None are both case classes):
  1. scala>val tree = Node( "root",
  2.      |                  Some(Node( "left", None, None)),
  3.      |                  Some(Node( "right", None, Some( Node( "grandchild", None, None) ) ) )
  4.      |                )
  5. tree: Node = Node(root,Some(Node(left,None,None)),Some(Node(right,None,Some(Node(grandchild,None,None)))))
  6. // you can deconstruct a datastructure made of cases classes
  7. scala> tree match {
  8.      | case Node( _, Some(left), Some(right) ) => println(left, right)
  9.      | case _ => println( "shouldnt happen" )
  10.      | }
  11. (Node(left,None,None),Node(right,None,Some(Node(grandchild,None,None))))
  12. scala>caseclass DataStructure( value1:String, value2:Int, value3:String)
  13. defined class DataStructure
  14. scala>  val d = DataStructure("one", 2, "three")
  15. d: DataStructure = DataStructure(one,2,three)
  16. scala> d.toString
  17. res0: String = DataStructure(one,2,three)
  18. scala> d == DataStructure("one", 2, "three")
  19. res1: Boolean = true
  20. scala> d == DataStructure("zero",1, "two")
  21. res2: Boolean = false
  22. scala> d.hashCode
  23. res4: Int = 1652907895
  24. // Only available in Scala 2.8
  25. scala> d.copy( value3="newValue")
  26. res5: DataStructure = DataStructure(one,2,newValue)

1 comment:

  1. Did you perhaps forget to include the definition of the Node case class?

    e.g.
    case class Node(name:String, left:Option[Node], right: Option[Node])

    ReplyDelete