r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
403 stars 56 forks source link

Comparing two objects of the same R6 class for equality #211

Closed daattali closed 3 years ago

daattali commented 3 years ago

I might be overlooking something very simple, but I could not find this concept natively supported in R6. Given two objects that are instantiated from the same R6 class, and may not be 100% fully identical, it can still be useful to have an equality method to test whether the two are practically equal. (Similar to Java's boolean equals(Object obj) or python's __eq__(self, other))

gaborcsardi commented 3 years ago

Typically the user needs to provide information on how to compare R6 objects.

== is an S3 generic, so you can define an S3 method for your class. You'll have to use obj$.__enclos_env__$private if you need to get to the private members of the object to perform the comparison. Many packages use this already, so I would say it is OK to use it at this point.

If you don't want a == operator, then you can also define a member function and then write obj1.is_equal(obj2).

daattali commented 3 years ago

Thanks Gabor. So there isn't a special R6-specific way to do this, that was what I was wondering about. 👍

mmuurr commented 3 years ago

== is an S3 generic, so you can define an S3 method for your class. You'll have to use obj$.__enclos_env__$private if you need to get to the private members of the object to perform the comparison. Many packages use this already, so I would say it is OK to use it at this point.

@gaborcsardi do you happen to know of any such (good, in your opinion) implementations that we may be able to have a peek at to help work out the proper pattern here? I'm particularly curious about how one might then also implement all.equal, as that seems to be the S3 generic commonly-used by other high-level packages for comparing objects.

gaborcsardi commented 3 years ago

I am not aware of any implementations, sorry. You are a pioneer here I am afraid.