0

Lets say I have

library(R6)

Person <- R6Class("Person",
              public = list(
                name = NULL,
                hair = NULL,
                initialize = function(name = NA, hair = NA) {
                  self$name <- name
                  self$hair <- hair
                  self$greet()
                },
                set_hair = function(val) {
                  self$hair <- val
                },
                greet = function() {
                  cat(paste0("Hello, my name is ", self$name, ".\n"))
                }
              )
)

PersonWithSurname <- R6Class("PersonWithSurname",
                         inherit = Person,
                         public = list(surname = NA,
                                       initialize = function(name, surname, hair) {
                                         super$initialize(name, hair)
                                         self$surname <- surname
                                       })
)

Then on the R console I have say,

newobject <- Person("Ann", "black")
Hello, my name is Ann.

Is there a way where I can now use the above object without re-using the name or re-writing code in the inherited object

e.g. I do not want to do

inheritObject <- PersonWithSurname$new("Ann", "Doe", "black")
Hello, my name is Ann.

Because I am repeating the "Ann" and the "black", ideally I would just want

inheritObject <- PersonWithSurname$new("Doe")
Hello, my name is Ann.

And it would keep all the properties.

Thanks in advance.

Lily
  • 65
  • 6

1 Answers1

1

You could do something like:

PersonWithSurname <- R6Class("PersonWithSurname",
                         inherit = Person,
                         public = list(surname = NA,
                                       initialize = function(name, surname, hair) {
                                         if (inherits(name,"Person")) super$initialize(name$name, name$hair) else
                                         super$initialize(name, hair)
                                         self$surname <- surname
                                       })
)

As you can see, I allowed in your constructor to provide a Person object, instead of a character defining the name. Trying it:

inheritObject<-PersonWithSurname$new(newobject,"Doe")
#Hello, my name is Ann.
nicola
  • 24,005
  • 3
  • 35
  • 56
  • I quite like that approach altough a [second constructor](https://stackoverflow.com/questions/35881234/user-constructor-for-r6-class-in-r) might be more elegant. – Gregor de Cillia Sep 17 '17 at 03:52