I've been searching around for an answer to this and couldn't really find anything.
In regards to generics, nim seems to work differntly than what I am used to. In langauges like Kotlin, Typescript, or even Dart - they use control flow based type analysis.
So the code below will work just fine
type SomeType[T] = ref object
proc echoTuple(tup: tuple) =
echo tup
proc echoString(str: string) =
echo str
proc example*[T](data: T): SomeType[T] =
if data is string:
echoString data
elif data is tuple:
echoTuple data
example "name"
Instead I get an error saying
type mismatch: got <string>
but expected one of:
proc echoTuple(tup: tuple)
first type mismatch at position: 1
required type for tup: tuple
but expression 'data' is of type: string
expression: echoTuple data
In a language with control flow based type analysis the data param would automatically be cast to a tuple after the is check.
I'm sure there are valid reasons that nim doesn't behave this way (which I am so far unaware of). My question is what's the idiomatic way of dealing with these scenarios in nim? Casting doesn't work, so would I be correct to assume that overloading the proc is how this is normally handled?
Thanks.
You need to use when for compile-time conditions:
type SomeType[T] = ref object
proc echoTuple(tup: tuple) =
echo tup
proc echoString(str: string) =
echo str
proc example*[T](data: T): SomeType[T] =
when data is string:
echoString data
elif data is tuple:
echoTuple data
discard example("name")
See https://nim-lang.org/docs/manual.html#statements-and-expressions-when-statement