Getting and Setting with Active Bindings

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

ch3_3-getting-and-setting-with-active-bindings.003.png

Object-Oriented Programming with S3 and R6 in R

 

 

     getting = read the data field

     setting = write the data field

Object-Oriented Programming with S3 and R6 in R

Active Bindings

 

 

     defined like functions

     accessed like data variables

Object-Oriented Programming with S3 and R6 in R
thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value",
    ..another_field = 123
  ),
  active = list(

a_field = function() {
if(is.na(private$..a_field)) { return("a missing value") }
private$..a_field
},
another_field = function(value) {
if(missing(value)) { private$..another_field } else {
assert_is_a_number(value)
private$..another_field <- value }
}
) )
Object-Oriented Programming with S3 and R6 in R
a_thing <- thing_factory$new()

a_thing$a_field
"a value"
a_thing$a_field <- "a new value"
Error in (function (value)  : a_field is read-only.
Object-Oriented Programming with S3 and R6 in R

 

a_thing$another_field <- 456
a_thing$another_field <- "456"
Error in (function (value) : is_a_number : 
value is not of class 'numeric'; it has class 'character'.
Object-Oriented Programming with S3 and R6 in R

Summary

  • Control private access with active bindings
  • Defined like functions
  • Accessed like data
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...