RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
399 stars 33 forks source link

Update `S7_class` `print()` method to show property default values #439

Open t-kalinowski opened 1 month ago

t-kalinowski commented 1 month ago

The current printout does not show the default values for properties. The default could be shown in the constructor or next to the property. Displaying it next to the property might make more sense; otherwise, constructor printouts will get long, and we'd need to implement line breaks in the constructor printout.

library(S7)

Person <- new_class(
  name = "Person",
  properties = list(
    # non-dynamic, default missing (required constructor arg)
    first_name = new_property(class_character, default = quote(expr = )),

    # non-dynamic, static default (optional constructor arg)
    middle_name = new_property(class_character, default = ""),

    # non-dynamic, default missing (required constructor arg) (same as first_name)
    last_name = new_property(class_missing | class_character),

    # non-dynamic, but defaults to the value of another property
    nick_name = new_property(class_character, default = quote(first_name)),

    # non-dynamic, optional constructor argument, read-only after construction.
    birthdate = new_property(
      class = class_Date,
      default = quote(Sys.Date()),
      setter = function(self, value) {
        if (!is.null(self@birthdate))
          stop("Can't set read-only property Person@birthdate")
        self@birthdate <- value
        self
      }
    ),

    # dynamic property, not a constructor argument
    age = new_property(class = class_any, getter = \(self) {
      Sys.Date() - self@birthdate
    })
  )
)
Person
#> <Person> class
#> @ parent     : <S7_object>
#> @ constructor: function(first_name, middle_name, last_name, nick_name, birthdate) {...}
#> @ validator  : <NULL>
#> @ properties :
#>  $ first_name : <character>             
#>  $ middle_name: <character>             
#>  $ last_name  : <MISSING> or <character>
#>  $ nick_name  : <character>             
#>  $ birthdate  : S3<Date>                
#>  $ age        : <ANY>