R6Point1Class: Version of R6 with heritable static/class methods and...

View source: R/result.R

R6Point1ClassR Documentation

Version of R6 with heritable static/class methods and attributes

Description

Elements in static can be called without instantiation, e.g. Class$method(). Functions are evaluated in the environment of Class, so you can refer to self (which is the class—not the instance—here) to create class methods.

Usage

R6Point1Class(..., static = NULL)

Arguments

...

Passed through to R6::R6Class

static

A named list of static/class functions/values to turn into methods/attributes. Note there is currently no differentiation between static and class methods at the moment; static methods are simply class methods that do not access self, though it will exist in their evaluation environment. This arrangement can be changed in the future if reason exists.

Why this exists

Sometimes we want static/class methods/attributes that can be accessed from the class (e.g. MyR6Class$my_static_method()) instead of an instance of that class (e.g. MyR6Class$new(...)$my_normal_method()). As individual classes are environments, these can be added after the fact like so:

MyR6Class <- R6Class(...)
MyR6Class$my_static_method <- function(x) ...

But the problem with the above is it's not heritable; if you make a class that inherits from MyR6Class, it will not have ⁠$my_static_method()⁠ unless you manually re-add it.

This class structure abstracts the pattern, so when you create a new class, it checks if the parent contains anything in private$static, and copies over any methods/attributes there, less any overwritten in the new class.

How static/class methods/attributes may be useful

There are lots of reasons you may want static/class methods/attributes, but the immediate use-case here is to create alternate methods for instantiating a class besides ⁠$new()⁠/⁠$initialize()⁠. For instance, if a class can be represented as JSON, it's quite helpful to have a ⁠$from_json()⁠ method that can recreate an instance from a JSON blob.

You could have a separate special reader function that returns an instance, but especially as classes multiply this solution becomes difficult to maintain.


ursa-labs/arrowbench documentation built on July 8, 2023, 11:36 a.m.