r-lib / R6

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

R6 doesn't like initialize() to use a parameter named like the class #195

Closed moodymudskipper closed 4 years ago

moodymudskipper commented 4 years ago

This was a bit of a pain to debug :

foo <- R6::R6Class("foo",
                   public = list(
                     foo = NULL,
                     initialize  = function(foo){}
                   ))
foo$new()
#> <foo>
#>   Public:
#>     clone: function (deep = FALSE) 
#>     foo: NULL
#>     initialize: function (foo)

adding body containing foo in initialize, I get a cryptic message

foo <- R6::R6Class("foo",
                   public = list(
                     foo = NULL,
                     initialize  = function(foo){foo}
                   ))
foo$new()
#> Error in .subset2(public_bind_env, "initialize")(...): argument "foo" is missing, with no default

Created on 2019-11-15 by the reprex package (v0.3.0)

I would suggest a more helpful error message, and maybe some documentation about this behavior (I didn't find any in the doc)

wch commented 4 years ago

I've made a change in 5cd8acd so that it now says:

Error in initialize(...) : argument "foo" is missing, with no default

Note that the cause of the error is the function (initialize) tries to use the foo argument, but you're calling initialize without providing a value for foo. You'll get that same error message if you call any R function that way, not just something from R6.