I just stumbled on one of Tony Morris' blog-posts about Java and a fundamental problem with the language: that of defining a bespoke equality-relation for a collection. This is something that I think is a big deal and wondered whether there was some scala solution.
The classic issue manifests itself in thinking about, say, a trade. Let's say I make two trades of +100 vodafone shares @150p. The two trades are equal, yes? Except they are not the same trade. In the case of a normal real-world system, with persistence or serialization, I cannot rely on identity to tell me whether two references are to the same trade!
So what I want is to be able to create a collection which I can pass an Equality-relation to:
val as = CleverSet[Trade](IdEquality)
val bs = CleverSet[Trade](EconomicsEquality)
How would I implement my set in an efficient manner (unless the EqualityRelation
also defines a hash
mechanism)?
trait EqualityRelation[T] {
def equal(t1: T, t2: T) : Boolean
def hash(t: T) : Int
}
So the questions are:
- Is there a library which provides this ability?
- Is there some way of doing this neatly in Scala?
It seems that with implicits, it would be quite an easy thing to add to the existing scala Set
type.
"Hello" === 2
does not compile – AccelerationEqual[List[Foo]]]
is parameterisable by anEqual[Foo]
. This goes half-way towards your goal. Martin Odersky declined to addHash[T]
to the standard library, saying that "we want to maintain universal hashing, it's too much part of the Java culture." scala-lang.org/node/4091#comment-16327 – Nealy