I want to return different data type depending on the input to a function.
Example:
func get(n: Int): __ {
if (n ==0) {
return 100;
}
else {
return “Test String”;
}
}
What type should we fill in the bracket?
Is there a way to mention the return type can be either Nat or Text or someotherthing
Thanks
There’s an or
type operator, but it would return the supertype, which in your case is Any
I believe.
I don’t think there’s a way to specifically return a Nat
or Text
… I may be wrong…
1 Like
Ori
3
Your function could return a tagged variant: https://smartcontracts.org/docs/candid-guide/candid-types.html#type-variant
See “Corresponding Motoko type” further down the page for an example.
2 Likes
Ah yeah, this is the right approach. Can’t believe I forgot about that.
2 Likes
For the viewers at home 
func get(n : Int) : { #nat : Nat; #text : Text; } {
if (n == 0) {
return #nat 100;
} else {
return #text "Test String";
}
};
1 Like