I've recently found this working:
const Mode = 0
var x: int | string | seq[int | string] = (
when Mode == 0:
0
elif Mode == 1:
""
elif Mode == 2:
@[0]
else:
@[""]
)
echo(x, " ", typeof(x), " ", sizeof(x))
I couldn't image it to even work, but it does. This is not dynamic typing but nearly the same.I may be missing something, what new abilities does this grant you?
To me this looks like you determine the type at compile-time and assign a default value, after that you face the same limitation as if you had written var x = 0. Figuring out which code gets written there is just a tad harder than before.
You can write same code without type class:
const Mode = 0
var x = when Mode == 0:
0
elif Mode == 1:
""
elif Mode == 2:
@[0]
else:
@[""]
echo x
Unlike if expression, when expression doesn't require each expressions in each branches are same. I don't think type classes are useful when declaring variables.
what new abilities does this grant you?
Not needing to write:
when Mode == 0:
var someVeryLongName = 0
elif Mode == 1:
var someVeryLongName = ""
elif Mode == 2:
var someVeryLongName = @[0]
else:
var someVeryLongName = @[""]