- parse_type_params(): accepts an optional `<T, U, ...>` list after a class/interface/trait name and records the names. - The declaration is tagged `__generic` with the comma-joined parameter list (e.g. "T" or "K,V"). Parameters are an erasure model: they are compile-time only, so a generic class is an ordinary class at runtime. - tests/generics.cat + suite: generic class, generic interface, a class implementing a generic interface, and a two-parameter class. Suite 152 -> 155.
33 lines
872 B
Plaintext
33 lines
872 B
Plaintext
-- tests/generics.cat -- generic type parameters (erasure model).
|
|
--
|
|
-- `class Box<T>` / `interface Container<T>` accept a `<T, ...>` parameter
|
|
-- list. Parameter names are compile-time only (erased at runtime), so a
|
|
-- generic declaration is an ordinary class/interface tagged with its
|
|
-- parameters in `__generic` -- structural, like the rest of the typing.
|
|
|
|
class Box<T>
|
|
function init(self, v) self.v = v end
|
|
function get(self) return self.v end
|
|
end
|
|
|
|
interface Container<T>
|
|
function size(self) end
|
|
end
|
|
|
|
class Vec implements Container
|
|
function size(self) return 3 end
|
|
end
|
|
|
|
local b = Box("hi")
|
|
print("box:", b.get(), b::__generic)
|
|
|
|
local v = Vec()
|
|
print("vec:", v.size(), v is Container)
|
|
|
|
-- two parameters
|
|
class Pair<K, V>
|
|
function init(self, k, val) self.k = k self.val = val end
|
|
end
|
|
local p = Pair("x", 9)
|
|
print("pair:", p.k, p.val, p::__generic)
|