Hello,

We're comparing Nim to java, and are stumped by some design notions and would 
like some clarification.

For example, Java has the object class, which provided default equals and 
hashcode methods that objects need to override to get the equality right.

What's the best way to do that in nim? We tried overriding `==` but we have a 
couple of issues: 1- we cannot compare two objects that are not `of` the same 
type. 2- we're not sure about the order of operation. For example, when we do 
ob1 == ob2, which `==` method gets called? 3- the examples tell us to use 
`proc`. However, that broke symmetry with the subtype when we added them to a 
HashSet, which meant we had to use `method`. 4- using a parameter type object 
did not work, and the parameter type auto only accepted objects of the same 
type as the class, which means you need to do extra steps when you don't know 
the type you're comparing your object with (type checking). Why? Why not return 
false, or compare the object reference as if `==` was not overridden?

Example:

Type 1: Person 
    
    
    type
      Person* = ref object of RootObj
        name*: string
        age*: int
    
    method `==`*(this: Person, other: any) : bool {.base.} =
        if (not(other of Person)):
            result = false
        else:
            var p2: Person = (Person) other
            if (this.name == p2.name and this.age == p2.age) :
                result = true
            else:
                result = false
    
    method hash*(x: Person): Hash {.base.}=
        var h: Hash = 0
        h = h !& hash(x.name)
        h = h !& hash(x.age)
        result = !$h
    
    
    Run

Type 2: Professional 
    
    
    type
      Professional* = ref object of Person
        specialty*: string
    
    method `==`*(this: Professional, other: auto) : bool =
        if (not(other of Professional)):
            result = false
        else:
            var p2: Professional = (Professional) other
            if (this.name == p2.name and this.age == p2.age and this.specialty 
== p2.specialty) :
                result = true
            else:
                result = false
    
    method hash*(x: Professional): Hash =
      var h: Hash = 0
      h = h !& hash(x.name)
      h = h !& hash(x.age)
      h = h !& hash(x.specialty)
      result = !$h
    
    
    Run

I can provide examples where proc breaks asymmetry.

Thanks, Abdullah 

Reply via email to