[Rd] General "nil" reference class object

Jon Clayden jon.clayden at gmail.com
Wed May 4 15:09:58 CEST 2011

Dear John and others,

I've been wondering about whether there's any way to indicate a "nil"
reference class object, which will represent "no value", and be tested
for, but not fail the internal type checking. NULL is the obvious
choice (or seems so to me), but can only be used if an explicit class
union is created:

> Foo <- setRefClass("Foo")
> Bar <- setRefClass("Bar", fields=list(foo="Foo"))
> Bar$new(foo=NULL)
Error in as(value, "Foo") :
  no method or default for coercing "NULL" to "Foo"
> setClassUnion("FooOrNull", c("Foo","NULL"))
[1] "FooOrNull"
> Bar <- setRefClass("Bar", fields=list(foo="FooOrNull"))
> Bar$new(foo=NULL)
An object of class "Bar"
<environment: 0x10392c4a0>
> is.null(Bar$new(foo=NULL)$foo)
[1] TRUE

Other languages allow things like "MyClass object = null", and it
seems to me that it would be helpful to have a value which will always
give TRUE for "is(object,<AnyReferenceClassName>)", but will
specifically indicate a nil reference. One possible ad-hoc solution is
to define the "empty" object of a base class to be "nil" (see below),
but it seems like it would be better to have a value specifically
designed for this purpose.

> nilObject <- Foo$new()
> is.nilObject <- function (x) identical(x,nilObject)
> Bar <- setRefClass("Bar", fields=list(foo="Foo"), methods=list(
+ initialize=function (foo=nilObject) { initFields(foo=foo) }))
> is.nilObject(Bar$new()$foo)
[1] TRUE

Is there already something like this that I'm not aware of? If not,
would it be possible and generally desirable to create it?

All the best,

Jonathan D Clayden, PhD
Lecturer in Neuroimaging and Biophysics
Imaging and Biophysics Unit
UCL Institute of Child Health
30 Guilford Street
United Kingdom

More information about the R-devel mailing list