OneBite.Dev - Coding blog in a bite size

declare a class in R

Code snippet on how to declare a class in R

class MyClass {
  
  # create a constructor
  MyClass <- function(x) {
    # set initial value for the object
    x <- x
  }
  
  # create a method to print the value
  print_value <- function() {
    print(x)
  }
  
  # create a getter
  get_x <- function() {
    return(x)
  }
  
  # create a setter
  set_x <- function(new_x) {
    x <- new_x
  }
}

This snippet of code demonstrates how to declare a class in R, named “MyClass”. The class has 4 features, a constructor, a method, getter and setter. The constructor is a function with 1 parameter “x”, which set the initial value to the object. The “print_value” is a method to print out the value of “x” from the object. The “get_x” and “set_x” serve as respectively, a getter and setter for the value of “x”. The getter will return the value of “x” and the setter will assign a new value to “x”.

r