Skip to content

Allow read-only properties to be set in the constructor #404

Closed
@guslipkin

Description

@guslipkin

Currently the documentation suggests that read-only properties (those with only a getter and no setter) are for computed values such as now or calculating using other properties of the object. However, sometimes you want to create an object with a value that doesn't change, isn't allowed to change, and isn't calculated from other values.

Take this person class, for example. We want to allow the birthdate to be set once and only once on construction, but the person's age will be calculated using the current date.

person <- S7::new_class(
  name = 'person',
  properties = list(
    'name' = S7::class_character,
    'birthdate' = S7::new_property(
      class = S7::class_Date,
      getter = \(self) { self@birthdate }
    ),
    'age' = S7::new_property(
      class = S7::class_any,
      getter = \(self) { Sys.Date() - self@birthdate }
    )
  ),
  constructor = \(name, birthdate) {
    S7::new_object(
      S7::S7_object(),
      'name' = name,
      'birthdate' = birthdate
    )
  }
)

person('Unixtime', as.Date('1970-01-01'))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions