Just a quick point of clarification: is it correct that nim can only do overloading in terms of parameter types and ignores the return type?
For example, the following code would generate a compiler error:
proc by_two(val: int): int =
result = val * 2
proc by_two(val: int): string =
result = $val & " and " & $val
var
x: int = 3
a: int
b: string
a = x.by_two()
b = x.by_two()
echo a
echo b
The compiler error is
Error: ambiguous call; both test2.by_two(val: int)[declared in test2.nim(2, 5)] and test2.by_two(val: int)[declared in test2.nim(5, 5)] match for: (int)
This is something I came across while writing a framework library. Any suggestions for working around this?
Essentially, with my framework, the programmer inherits an object and overrides various methods as needed before running the main algorithm. One of the methods could either return a sequence (faster) or a table (slower but adds descriptions while running). In my Python version of the library, its the same procedure. But with strong static typing, it clearly can't work in the same way in Nim.
One workaround I've come across already is adding the return var to the parameters:
proc by_two(val: int, dummy: int): int =
result = val * 2
proc by_two(val: int, dummy: string): string =
result = $val & " and " & $val
var
x: int = 3
a: int
b: string
a = x.by_two(a)
b = x.by_two(b)
echo a
echo b
Kind of confusing, but it works. Any suggestions?
Thanks in advance for any help with this!
You can send the type as an argument, either as a generic or as a typedesc parameter:
let x = 3
proc by_two(val: int, T: typedesc[int]): int =
result = val * 2
proc by_two(val: int, T: typedesc[string]): string =
result = $val & " and " & $val
let a = x.by_two(int)
let b = x.by_two(string)
echo a
echo b
proc by_two[T: int|string](val: int): T =
when T is int:
result = val * 2
elif T is string:
result = $val & " and " & $val
let c = x.by_two[:int]()
let d = x.by_two[:string]()
echo a
echo b