4

In Python we can make a new class iterable by adding __iter__. Can we do something like this in R with R6 class (or any class)?

For example:

my_list_class <- R6Class("my_list_class",
    public = list(
      elem = list(),
      initialize = function(x=list()) {
         self$elem = as.vector(x)
      }    
    )
)

I would like to following functionality

my_list <- my_list_class$new(c(1,2,3,4,5))

for (l in my_list) { print(l) }
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5

Although I know with this example, for (l in my_list$elem) will work.

Any answer would be very appreciated.

morningfin
  • 329
  • 2
  • 10

0 Answers0