r-lib / R6

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

using obj$set to create NULL object #158

Closed yonicd closed 6 years ago

yonicd commented 6 years ago

I want to add a new public element with a value NULL in an R6Class using obj$set.

Intuitively I would do

obj$set('public','foo',NULL)

But the way obj$set is written if I want to add a new element with NULL value it is removed from the group list

https://github.com/r-lib/R6/blob/bb562135dc51d6750b9d5c6e7f392bcdfb0859b7/R/generator_funs.R#L70

Simple <- R6::R6Class("Simple",
                  public = list(
                    x = 1,
                    getx = function() self$x
                  )
)

Simple$set('public','foo',NULL)

Simple$public_fields
#> $x
#> [1] 1

Created on 2018-09-24 by the reprex package (v0.2.1)

It would need to be

value <- list(NULL)
self[[group]][name] <- value

If I put in obj$set('public','foo',list(NULL)) then I get back a list object which is not what I intended.

Simple <- R6::R6Class("Simple",
                  public = list(
                    x = 1,
                    getx = function() self$x
                  )
)

Simple$set('public','foo',list(NULL))

Simple$public_fields
#> $x
#> [1] 1
#> 
#> $foo
#> $foo[[1]]
#> NULL

Created on 2018-09-24 by the reprex package (v0.2.1)

Is there a way to do this now that I can't see?

wch commented 6 years ago

I agree that would make more sense for Simple$set('public', 'foo', NULL) to set foo to NULL than it would to remove foo. I'll make that change.