Reputation: 1786
I can declare a proc to return a "union type", but cannot actually return values of more than one type:
proc test(b: bool) : int|string =
if b: 1 else: "hello"
echo test true
echo test false
Expected:
1
hello
Actual:
Error: type mismatch: got 'string' for '"hello"' but expected 'int literal(1)'
Even if I swap the return types (string|int
) the error is the same. I am only allowed to return an int
. I tried putting the return type in parens; and I tried using or
instead of |
. No dice.
What am I missing? (I don't want to use a variant object.)
The code can be tested online at the Nim Playground. I've scoured google and the Nim documentation, and come up empty.
Upvotes: 1
Views: 749
Reputation: 1719
Return types have to be known at compile time in Nim. Imagine you tried to return the result of that procedure to a string variable. Now you're in a scenario where one return value works, but the other would be a compilation error. In order to allow Nim to figure out whether to throw an error or not it must be able to figure out which type will be returned at compile time. The solution here is to use a static[bool]
and a when
in place of the if
. If you actually need a type that can hold different types on runtime you have to use variant objects.
Upvotes: 4