Sum data type: Difference between revisions
→{{header|Wren}}: Minor tidy and added a second version using Union class.
(→{{header|Wren}}: Minor tidy and added a second version using Union class.) |
|||
Line 730:
In the following example, the Variant type can only accept numbers or strings.
<syntaxhighlight lang="
construct new(v) {
// restrict 'v' to numbers or strings
Line 757:
[six, String]
Value must be a number or a string.
[./
[./
[./
</pre>
{{libheader|Wren-dynamic}}
We can also automate the process using the Union class from the above module.
<syntaxhighlight lang="wren">import "./dynamic" for Union
var Variant = Union.create("Variant", [Num, String])
var v1 = Variant.new(6)
System.print([v1.value, v1.kind])
var v2 = Variant.new("six")
System.print([v2.value, v2.kind])
var v3 = Variant.new([6]) // will give an error as argument is a List</syntaxhighlight>
{{out}}
<pre>
[6, Num]
[six, String]
Invalid type.
[./dynamic line 4] in init new(_)
[./dynamic line 6] in
[./Sum_data_type_2 line 9] in (script)
</pre>
|