I'm playing around with S7 and abstract classes. I've encountered a scenario where a custom print method is being dispatched before the validation occurs. I think this might be because the validation is lazy? My expectation is that validation would happen before a print method is dispatched.
library(S7)
#> Warning: package 'S7' was built under R version 4.3.1
Enum <- new_class(
"Enum",
properties = list(
Value = class_character,
Variants = class_character
),
validator = function(self) {
if (length(self@Value) != 1L) {
"enum value's are length 1"
} else if (!(self@Value %in% self@Variants)) {
print(self)
"enum value must be one of possible variants"
}
},
abstract = TRUE
)
enum_class <- "GridShape"
variants = c("Square", "Hexagon")
GridShape <- new_class(
enum_class,
parent = Enum,
properties = list(
Value = class_character,
Variants = new_property(class_character, default = variants)
)
)
# print method for enums
# since this is an abstract class we get the first class (super)
# to print
print.Enum <- function(x, ...) {
cat(class(x)[1], "::", x@Value, sep = "")
invisible(x)
}
GridShape("Square")
#> GridShape::Square
GridShape("sdfs")
#> GridShape::sdfs
#> Error: <GridShape> object is invalid:
#> - enum value must be one of possible variants
I'm playing around with S7 and abstract classes. I've encountered a scenario where a custom print method is being dispatched before the validation occurs. I think this might be because the validation is lazy? My expectation is that validation would happen before a print method is dispatched.
Created on 2023-11-10 with reprex v2.0.2