Consider this开发者_高级运维 code:
val a = new { val x = 1; val y = 2 }
val b = new { val x = 1; val y = 2 }
a == b // false
Wouldn't it be sensible if anonymous classes would have some equality defined which would return true, if fields/methods/values are the same?
I imagine that this could also reduce the number of class files Scala has to generate in certain use cases.
(As far as I know C# uses the same class for anonymous types if they have the same values in the same order and returns true
when those get compared to each other.)
Because it's difficult to do the right thing in all cases.
Generally, in OO languages, equality is only meaningful between instances of the same class. When you're using anonymous classes the way you do in the question, you actually have two different classes which happen to look the same.
Consider (in pseudocode):
class Point {
int x;
int y;
}
class Dimensions {
int x;
int y;
}
class Rectangle {
Point lowerLeftCorner;
Dimensions dimensions;
}
Here a Point should never compare equal to a Dimensions, even if they have the same x and y value. But two Points with the same x and y values should compare equal.
In your example, how is the language to magically know if you intended the two different anonymous classes to have the same meaning or not? They could conceptually be two Points, or a Point and a Dimensions.
(I disagree that C#'s system is better: first, it doesn't know that your anonymous classes were intended to be comparable; and second, i really don't see why order should affect things. In all other cases, the order of the fields of a class doesn't matter; why should it matter here?)
精彩评论