r-lib / R6

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

[question] How to access output of a method? #87

Closed RanaivosonHerimanitra closed 8 years ago

RanaivosonHerimanitra commented 8 years ago

Sorry, if It sounds obvious. To extend the basic example provided by the vignette , I'd like to access output of a method greet (is it a method?) as follows:

Person <- R6Class("Person",
                  public = list(
                    name = NA,
                    hair = NA,
                    initialize = function(name, hair) {
                      if (!missing(name)) self$name <- name
                      if (!missing(hair)) self$hair <- hair
                      self$greet()
                      x=self$greet()
                      print(x)
                      if (x=="Hello, my name is Ann.") {
                         cat("You can access it!")
                      }
                    },
                    set_hair = function(val) {
                      self$hair <- val
                    },
                    greet = function() {
                      cat(paste0("Hello, my name is ", self$name, ".\n"))
                    }
                  )
)

It returns NULL however. thanks in advance, Herimanitra,

wch commented 8 years ago

The cat() prints output to the console, but it returns NULL. You just need to take out the cat() and have something like:

greet = function() {
  paste0("Hello, my name is ", self$name, ".\n")
}