- `trait` keyword: like `interface`, but tagged `__trait`; its methods carry default bodies. A class that `implements` a trait has those bodies mixed in (a class's own method wins), then is checked structurally -- so the mix-in runs BEFORE `__implements_check`. - runtime `__trait_mixin(cls, trait)`: copies a trait's default methods into the class (skipping `__*` meta keys and existing members). - `Sized` -- the marker object for "layout known at compile time"; every concrete value satisfies it, so `x is Sized` / `implements(x, Sized)` hold and signatures can name it (`buf : Sized()`). - tests/traits.cat + suite: default method, override, `is`, and Sized. Suite 144 -> 151.
36 lines
1.1 KiB
Plaintext
36 lines
1.1 KiB
Plaintext
-- tests/traits.cat -- traits: interfaces with default methods (mix-in).
|
|
--
|
|
-- A `trait` is an interface whose methods carry default bodies. A class
|
|
-- that `implements` it gets those bodies mixed in (unless it defines its
|
|
-- own), and satisfies the trait structurally. Methods take explicit
|
|
-- `self`, like every method in catscript.
|
|
|
|
trait Greeter
|
|
function greet(self) return "hello, " .. self.name end
|
|
function loud(self) return "HELLO, " .. self.name end
|
|
end
|
|
|
|
class Person implements Greeter
|
|
function init(self, n) self.name = n end
|
|
end
|
|
|
|
-- a class may override a trait's default method
|
|
class Robot implements Greeter
|
|
function init(self, n) self.name = n end
|
|
function greet(self) return "beep " .. self.name end
|
|
end
|
|
|
|
local p = Person("Marcel")
|
|
print(p.greet())
|
|
print(p.loud())
|
|
print("person is Greeter:", p is Greeter)
|
|
|
|
local r = Robot("R2")
|
|
print(r.greet())
|
|
print(r.loud())
|
|
print("robot is Greeter:", r is Greeter)
|
|
|
|
-- Sized(): every concrete value has a known layout, so it is satisfied
|
|
print("sized:", p is Sized)
|
|
print("implements Sized:", implements(p, Sized))
|