What is idiomatic pattern for TclOO object equals
implementation?
Perhaps compare concatenated sorted lists of all properties?
Are there analogs to Scala case classes?
What is idiomatic pattern for TclOO object equals
implementation?
Perhaps compare concatenated sorted lists of all properties?
Are there analogs to Scala case classes?
TclOO defines no equality system for you by design; as the objects are in general modifiable, there's no automatic notion that would apply other than object identity, and you can just compare the name of the object to get that (or the results of info object namespace $theObj
, if you're being very paranoid; I think Tcl 8.7 will provide more options, but that's not yet accepted).
If you want to define an equality system such as you are proposing, you could do this:
oo::class create PropertyEquals {
method equals {other} {
try {
set myProps [my properties]
set otherProps [$other properties]
} on error {} {
# One object didn't support properties method
return 0
}
if {[lsort [dict keys $myProps]] ne [lsort [dict keys $otherProps]]} {
return 0
}
dict for {key val} $myProps {
if {[dict get $otherProps $key] ne $val} {
return 0
}
}
return 1
}
}
Then you just need to define a properties
method on the class you might be comparing, and mix in the equals
method from the above.
oo::class create Example {
mixin PropertyEquals
variable _x _y _z
constructor {x y z} {
set _x $x; set _y $y; set _z $z
}
method properties {} {
dict create x $_x y $_y z $_z
}
}
set a [Example new 1 2 3]
set b [Example new 2 3 4]
set c [Example new 1 2 3]
puts [$a equals $b],[$b equals $c],[$c equals $a]; # 0,0,1
Note that Tcl doesn't provide complex collection classes like some other languages (because it has array-like and mapping-like open values) and so doesn't need an object equality (or content hashing) framework to support that.