Scala Corner Case#3: "object" or "case object" Extends Case Class? It's a Different Story
Case class in Scala is a neat feature, it automatically generates apply, extract and equals functions. But I encountered a strange "equals" behavior today, which wasted me 2 hours to find why.
Define a simple case class "Symbol", then a "VarSymbol" which extends "Symbol" with one more field "name:String". We know you can compare the equality of instances of "VarSymbol" by this "name", Scala automatically gets it right. And of course, a direct instance from "Symbol()" should not equal to any "VarSymbol", since it lacks "name" field, that's right.
case class Symbol() case class VarSymbol(name:String) extends Symbol
Then, I need a singleton object "NoSymbol", I defined it as:
object NoSymbol extends Symbol
I of course thought this "NoSymbol" should not equal any "VarSymbol" instance, or,
NoSymbol == VarSymbol("I'm var")
Should return false. But life is not so straightforward, it returns true in real life !!!
I finally got my code working, by adding a "case" before "object NoSymbol extends Symbol". This "NoSymbol" won't equal any "VarSymbol" now, I'm grad things finally go back in track.
I don't know if it's a Scala bug, or, that's what Scala thinks it should be: all "Symbol" and it's inherited instances should equal "NoSymbol" object. Anyway, here's the whole code for test:
case class Symbol()
case class VarSymbol(name:String) extends Symbol
object NoSymbol extends Symbol
case object CasedNoSymbol extends Symbol
object TestCaseObject {
def test = {
val noSym = NoSymbol
val caseNoSym = CasedNoSymbol
val varSym = VarSymbol("I'm var")
if (noSym == varSym) println("NoSym equals varSym !")
else println("NoSym doesn't equal varSym")
if (caseNoSym == varSym) println("CaseNoSym equals varSym !")
else println("CaseNoSym doesn't equal varSym")
}
}
Run TestCaseObject.test, I got:
NoSym equals varSym ! CaseNoSym doesn't equal varSym

rss
Comments
The behaviour with object is actually correct behaviour (and this fact should be obvious when you think about it the right way).
You've got case class Symbol. This defines equals because it's a case class. It has an empty argument list, so all Symbols are equal. You extend it without defining a new equals method. Therefore it inherits the equals method. You now pass it a Symbol object (the fact that the object you passed overrides equality is irrelevant), which it declares to be equal because all symbols are equal. Meanwhile VarSymbol? has overridden equals so *doesn't* think it's equal. It's a classic example of equality + subtyping being broken.
There are a bunch of additional related issues here. Hopefully some of them will improve. But basically I would strongly encourage you to not use inheritance of case classes (i.e. one case class extending another), now or ever. Make your base class non-case.
The "Effective Java" book item on equality (item 7 or item 8) is a good read on the subject of equality and subtyping.
However, re-reading your post and that item, I am wondering: what if a class and its subclass (Point and ColorPoint? in the book example) were NEVER equal. This wouldn't break symmetry nor transitivity. What would be lost then?
@David, @Eric, thanks for the explanation and information. When I call "varSym == noSym", it will return false, it hints at that the object NoSym?'s seems to implement "equals" via "instanceOf" instead of "getClass" ?.
Exactly, that's how it's implemented in the Symbol class.
Here is a follow-up from Joshua Bloch on using instanceof vs getClass. This answers my question about the risks of using getClass: http://www.artima.com/intv/bloch17.html.
This is very much happy for providing the great services in this blog that to sharing the great technology in this blog. Thanks a lot for providing the great info is visible in this blog that to using the great technology in this blog Link:md5 php
No one can deny the shopping at the coach factory outlet is satisfactory. For the low prices and good quality.Over the years, coach factory online has added a multitude of new handbag shapes, styles and materials to their collection. However, the highest care is taken that every Coach handbags is both aesthetically beautiful and functional.Many fashionable women match with practical Coach Purses which will make the street shopping become relaxed,and make every person can enjoy more diversiform combination in coach factory outlet online.
http://www.ccoachfactoryoutlet.com
Don't feel upset, there will be a great conversion to this kind of situation because there are a large number of louis vuitton sale now!louis vuitton outlet,welcome to buy urban louis vuitton on our online shop.discount price is our special offer, durability and high quality is our promise.louis vuitton Outlets offer famous classic brand for LV,Channel, with perfect service.So become to the VIP soon.They offer more new styles,like LV purses,LV wallets etc. And are tested by product quality monitoring center .
http://www.louisvuittonoutletsaleo.com
Turn your attention to such discount coach sneakers for women from coach outlet online, you will find something unique and special of such authentic coach for sale at coach factory outlet store online.coach outlet store sells goods that are constructed to meet the highest standards of quality and functionality.You can trust it 100 percent.coach outlet has become a popular shopping experience for consumers around the world, and a desirable distribution channel for manufacturer's and retailers.
http://www.coachoutletonlinesl.com
Our online store offers you discounted Designer louis vuitton replica wallet at present. You could find them in desirable quality and price. If you don't mind high class louis vuitton uk, have a good time here.These is the first time your visit our louis vuit Louis vuitton online shop ,welcome.
http://www.louisvuittonukk.org.uk
coach outlet store online marketed properly all greater compared to earth and earn cozy praise from customers. They are made from the finest leather and fabric.coach outlet store have Coach handbags,Coach Shoulder Bags,Coach Briefcases and so on,these bags are so perfectly reproduced,you won't even be able to tell the difference!Coach Outlet Online Store would dynamically change your overall styles right away. The amazing knack about the unique coach handbag is that it would never disappoint your individual styles at all. Rather, it would instantly change your ultimate fashions in a remarkable manner.
http://www.coachoutletstoreonlineeo.com
any louis vuitton outlet New backpack features usa a function grownup overall look. Varied piece allows that it is captivated me within the approve and also further than your body.It’s induced by way of severe hardworking liver diseases, and also the most familiar factors behind constant louis vuitton bags outlet hard working liver disorder usually are excessive drinking and also liver disease Chemical.Ladies have an ardent love for the Louis Vuitton handbags outlet because Louis Vuitton enjoys a worldwide reputation of high quality and fashionable designs.
http://www.louisvuittonoutletbagsc.com
I am really very happy for the great services in this blog that to wonderful post are displays in this website. This website is proving the nice approach is visible in this blog and the nice technology is visible in this blog. super casino ladbrokes casino online casinos casino bonus Online Gambling
Welcome to order Discount Louis Vuitton UK and lead a fashionable, luxury and elegant life from our Louis Vuitton Canada Outlet Store. Enjoy the shopping now here! The Louis Vuitton Handbags are amazing and you will rest assured by proudly owning a bed that you will find yourself envied by simply your colleagues. Louis Vuitton Store Online Handbags can also bring great accuracy as well as practical applicability and fashionable.
http://www.uk-louisvuittonhandbags.co.uk
christian louboutin outlet christian louboutin uk
louis vuitton uk louis vuitton bags uk
mulberry outlet uk mulberry sale
Thank you very much for helpful info in this 777 Poker Games blog and the great technology is visible in this Blackjack Play Live blog. I am really very great for the info wise that to it is very much satisfied by the info in this 365 CASINO GAME blog. This is very much impressive for the nice info in this Casino Game Plan blog. I am really very happy for visiting the nice info in this top betting place website. Thanks a lot for once again sharing the nice info in this website.
This is really satisfied interview questions for u by the nice technology is Asp.net interview questions visible in this blog that to really Php interview questions enjoyed for providing the great .net interview questions approach is display in this SAP interview questions website. Thanks a lot for providing the nice technology in this blog.