Showing posts with label equals. Show all posts
Showing posts with label equals. Show all posts

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

Tuesday, August 25, 2009

Equals

One welcome change in Scala is the change of semantics of the == operator. In Scala it is the same as doing a .equals comparison in Java. If you want identity comparison you can use the eq method (and ne for the not equal comparator).

Examples:
  1. scala>caseclass Name(first:String, last:String)
  2. defined class Name
  3. scala>val jesse = Name("Jesse","Eichar")
  4. jesse: Name = Name(Jesse,Eichar)
  5. scala>val jesse2 = Name("Jesse","Eichar")
  6. jesse2: Name = Name(Jesse,Eichar)
  7. scala>val jody = Name("Jody","Garnett")
  8. jody: Name = Name(Jody,Garnett)
  9. scala>val jJames = Name("Jesse","James")
  10. jJames: Name = Name(Jesse,James)
  11. scala> jesse == jesse2
  12. res0: Boolean = true
  13. scala> jesse == jody
  14. res1: Boolean = false
  15. scala> jesse ne jesse2
  16. res2: Boolean = true
  17. scala> jesse eq jesse2
  18. res3: Boolean = false