r-lib / R6

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

Allow class-level members #226

Closed iqis closed 3 years ago

iqis commented 3 years ago

Some OO designs may make use of a class-level member. For example, incrementing a serial number:

Employee <- R6::R6Class("Employee", 
                        class_member = list(count = 0), 
                        public = list(
                            initialize = function(name){
                                self$name <- name
                                self$class$class_member$count <- 
                                    self$id <- 
                                    self$class$count + 1
                            }, 
                            id = NULL
                            name = NULL
                        ))
john <- Employee$new("John")
mary <- Employee$new("Mary")

john$id
# [1] 1
mary$id
# [1] 2

Depends on #225.

wch commented 3 years ago

This sounds similar to having Java-style static members: https://github.com/r-lib/R6/issues/222#issuecomment-737321910

iqis commented 3 years ago

Thanks, I think this is an exact duplicate... Wasn't using static when searching for existing issues.