RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
399 stars 33 forks source link

class_null #337

Closed jonthegeek closed 1 year ago

jonthegeek commented 1 year ago

For method dispatch, class_missing doesn't catch NULL (which it shouldn't, really). This works, but it doesn't feel quite right: class_null <- S7::new_S3_class("NULL"). Should class_null be in the base types?

jonthegeek commented 1 year ago

(ok, not per se, 'cuz you can't inherit from it... but guidance for how to dispatch for it would be helpful!)

hadley commented 1 year ago

You can just use a literal NULL:

library(S7)

g <- new_generic("g", "x")
method(g, NULL) <- function(x) "hello"
g(NULL)
#> [1] "hello"

Created on 2023-09-08 with reprex v2.0.2

This presumably should be documented somewhere.

jonthegeek commented 1 year ago

I could have sworn that didn't work! I wonder what I did. Thanks for the tip! 🙃

jonthegeek commented 1 year ago

Aha! This is (equivalent to) what I tried that failed:

library(S7)

g <- new_generic("g", "x")
method(g, class_missing | NULL) <- function(x) "hello"
#> Error in class_missing | NULL: operations are possible only for numeric, logical or complex types
g(NULL)
#> Error: Can't find method for `g(<NULL>)`.

Created on 2023-09-08 with reprex v2.0.2

vs

library(S7)

g <- new_generic("g", "x")
method(g, class_missing | new_S3_class("NULL")) <- function(x) "hello"
g(NULL)
#> [1] "hello"

Created on 2023-09-08 with reprex v2.0.2

I'm going with the separate method for NULL, but at least now I can see what tricked me!

hadley commented 1 year ago

Ah that I can fix.