Tuesday, November 24, 2009

Equals, Tuples and Case-classes

This is mostly a quick tip (or opportunity for refactoring).

Most of Scala's built in classes implement a useful equals and hashcode. The very commonly used case-classes and Tuple classes are the examples that spring to mind. So this enables the following options:
  1. // Assume Box is out of your control and you cannot refactor it into a case class
  2. scala> class Box(val name:Stringval minx:Intval miny:Intval maxx:Intval maxy:Int)
  3. defined class Box
  4. scala> val box = new Box("mybox", 0, 0, 10, 10)
  5. box: Box = Box@568bf3ec
  6. // before:
  7. scala> box.minx == 0 && box.miny == 0 && box.maxx == 10 && box.maxy == 10      
  8. res3: Boolean = true
  9. // after
  10. scala> import box._
  11. import box._
  12. scala> (minx,miny,maxx,maxy) == (0,0,10,10)
  13. res5: Boolean = true
  14. // another box definition:
  15. scala> case class Box2 (name:String, ul:(Int,Int), lr:(Int,Int)) 
  16. defined class Box2
  17. // case classes have nice equals for comparison
  18. scala> box2 == Box2("a nicer box", (0,0), (10,10))
  19. res6: Boolean = true
  20. // but what if you don't want to compare names
  21. scala> import box2._
  22. import box2._
  23. scala> (ul,lr) == ((0,0),(10,10))
  24. res7: Boolean = true

No comments:

Post a Comment