| new_trait | R Documentation |
new_trait() adds a nominal contract registry on top of S7 dispatch. A class
only has the trait after impl_trait() records the implementation, even if
compatible S7 methods already exist. Registrations belong to the current
R session and the particular trait descriptor, not its display name. Reuse
the same descriptor for registration and checks; deserializing a descriptor
does not transfer its registrations.
new_trait(
name,
methods = list(),
parents = list(),
assoc_types = character(),
assoc_consts = list(),
package = NULL
)
trait_method(
generic,
default = NULL,
name = NULL,
args = list(),
returns = S7::class_any
)
name |
For |
methods |
For |
parents |
Optional trait or list of supertraits. |
assoc_types |
Required associated type names, or a named list of default associated type values. |
assoc_consts |
Required associated constant names, or a named list of default constant values. |
package |
Optional package name used only for display. |
generic |
An S7 generic function. |
default |
Optional default implementation. If supplied, |
args |
Optional named list of S7 classes, interfaces, or traits for
runtime argument checking with |
returns |
Optional S7 class, interface, or trait for runtime return
checking with |
This makes default methods and associated metadata practical, but the result remains a runtime R abstraction. It does not emulate Rust's compile-time trait bounds, coherence, orphan rules, or type-checked associated types.
new_trait() returns an S7 object of class s7_trait.
trait_method() returns an S7 object of class s7_trait_method.
local({
area <- S7::new_generic("area", "x")
perimeter <- S7::new_generic("perimeter", "x")
Circle <- S7::new_class(
"Circle",
properties = list(r = S7::class_double)
)
Measurable <- new_trait(
"Measurable",
methods = list(
area = trait_method(area),
perimeter = trait_method(perimeter, default = function(x) NA_real_)
),
assoc_consts = c("UNITS")
)
impl_trait(
Measurable,
Circle,
methods = list(area = function(x) pi * x@r^2),
assoc_consts = list(UNITS = "unitless")
)
has_trait(Circle, Measurable)
trait_call(Measurable, "area", Circle(r = 2))
trait_assoc_const(Measurable, Circle, "UNITS")
})
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.