I am wondering if there is a way for a procedure/method to return values of multiple types in Nim. Specifically, for the following code, is it possible to write a wrapper method/procedure called getVal() that can return the value of the Literal (which can be both int or str)?
type # Literal
LiteralKind = enum lkSym, lkInt, lkFlt
Literal = ref object
case kind: LiteralKind
of lkSym: symVal: string
of lkInt: intVal: int
of lkFlt: fltVal: float
method getVal(l: Literal): ??? =
case l.kind:
of lkSym: result = l.symVal
of lkInt: result = l.intVal
of lkFlt: result = l.fltVal
method getVal(l: static[Literal]): auto =
when l.kind == lkSym:
result = l.symVal
when l.kind == lkInt:
result = l.intVal
when l.kind == lkFlt:
result = l.fltVal
I do this in https://github.com/jrfondren/nim-maxminddb/blob/master/src/maxminddb/node.nim#L61
For your case:
type
LiteralKind = enum lkSym, lkInt, lkFlt
Literal = object
case kind: LiteralKind
of lkSym: symVal: string
of lkInt: intVal: int
of lkFlt: fltVal: float
proc getVal[T](l: Literal): T =
template sel(t: typedesc, field: untyped): untyped =
when T is t: result = field
else: assert(false, "type error")
case l.kind:
of lkSym: sel(string, l.symVal)
of lkInt: sel(int, l.intVal)
of lkFlt: sel(float, l.fltVal)
echo type(Literal(kind: lkFlt, fltVal: 2.0).getVal[:float])
echo type(Literal(kind: lkSym, symVal: "2").getVal[:string])
echo Literal(kind: lkInt, intVal: 2).getVal[:int]
NB. generic methods are deprecated.