This puzzles me -- I have read the reasons Scala exists at all, and the common-sense presented appeals to me, for example choosing static typing (because of less errors). Yet, you can compare (out of the box, by default) completely different, irrelevant objects and it compiles and runs fine. For me it just begs for more errors in code.
Could someone please explain what are the reasons for such feature? Or benefits?
I know how Scala works in the matter of comparison. I am asking WHY it works that way.
I would expect, that if I want to do this, I would write implicit conversion or explicit comparison. That approach makes perfect sense for me, current Scala way -- no, and thus my question.
And one more thing -- I am not looking how to use Scala-way comparison for some fancy effects, I am looking for more strict error checking. IOW: I don't want to compare Orange and Apple by color, I want to forbid such comparison by default unless user explicitly say it is OK to compare such types.
val s : String = "ala"
val x : Int = 5
def main(args : Array[String])
val t = new Test
val f = new Foo
Well, the simple answer is that == is designed to be compatible with
java.lang.Object.equals(). Since any class can override
equals() it's impossible for the Scala compiler to determine the result of an equality check between two objects unless it knows the runtime class of the object at compile time (i.e. the static type must be a final class or the
new invocation must be visible to the compiler when compiling the equality check) AND the
equals() method is not overridden in this class or any super class.
So, in your example the compiler can indeed infer the runtime class of both
f and issue a warning (not an error though) for the equality check, but in practice the cases where the runtime class can be inferred are quite rare. Note that scalac already issues warnings for some equality comparisons between primitive types and object types.
P.S. If you want a safer equality check use the
Equal trait in Scalaz.