Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support S7 classes #68

Open
mvankessel-EMC opened this issue Nov 29, 2024 · 0 comments
Open

Support S7 classes #68

mvankessel-EMC opened this issue Nov 29, 2024 · 0 comments

Comments

@mvankessel-EMC
Copy link
Collaborator

library(S7)

# Class specification
Person <- new_class(
  "Person",
  properties = list(
    age = class_integer,
    name = class_character
  ),
  validator = function(self) {
    if (length(self@age) != 1) {
      "@age must be length 1"
    }  else if (self@age < 0) {
      "@age must be greater than or equal to 0"
    } else if (length(self@name) != 1) {
      "@name must be length 1"
    }
  }
)

person <- Person(age = 32L, name = "Steve")
person
#> <Person>
#>  @ age : int 32
#>  @ name: chr "Steve"

# Generic method specification
method(print, Person) <- function(Person) {
  cat(
    sprintf(
      "Name: %s\nAge: %s",
      Person@name, Person@age
    )
  )
}

print(person)
#> Name: Steve
#> Age: 32

# New generic
say <- new_generic("say", "x", function(x, ..., text) {
  S7_dispatch()
})

method(say, Person) <- function(x, text) {
  cat(
    sprintf(
      "%s says: %s.",
      Person@name, text
    )
  )
}

say(person, text = "stuff")
#> Person says: stuff.

Created on 2024-11-29 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant