Krux's solution is the most efficient. You can also use inheritance: 
    
    
    import strutils
    
    type
      BaseType = ref object of RootObj
      
      StringType = ref object of BaseType
        value: string
      IntType = ref object of BaseType
        value: int
    
    method toString(bt: BaseType): string {.base.} = ""
    method toString(st: StringType): string = st.value
    method toString(it: IntType): string = $it.value
    
    
    proc getArg(typeName:string, strValue:string):BaseType=
     case typeName:
      of "string":
        result = StringType(value: strValue)
      of "int":
        result = IntType(value: parseInt(strValue))
    
    
    let bt = getArg("int", "777")
    echo "ToString: ", toString(bt)
    
    if bt of StringType:
      echo("Casting: ", StringType(bt).value)
    elif bt of IntType:
      echo("Casting: ", IntType(bt).value)
    

[run it](https://glot.io/snippets/en6i60pzu6)

Reply via email to