`when` is resolved at compile-time, at run-time you get just one of two 
branches, which already knows what field to read from JSON and where to put it. 
So if you explicitly pass strategy (type disambiguator) as compile-time known 
(static) argument, a proc with `when` is the simplest and most performant way.

With those `foo` 's, in my example above `Something` type was not used and the 
variable was of a specialised type, so methods can be replaced with just procs 
too.

You'll need methods if you want variable of a general (`Something`) type and no 
explicit disambiguator:
    
    
    # using the code from previous example with `foo`'s, except the last 
paragraph
    
    # prettifying echo'ing
    method `$`(s: Special): string {.base.} = assert(false, "Kinda abstract")
    method `$`(s: SpecialisedTA): string = "[abc: " & s.abc & "]"
    method `$`(s: SpecialisedTB): string = "[def: " & s.def & "]"
    proc `$`(s: Something): string = "[a: " & $s.a & ", special: " & $s.special 
& "]"
    
    var jsonNode = parseJSON"""{"abc": "5", "def": "7"}"""
    var a: Something
    a.a = 3
    a.special = new SpecialisedTA
    # `a` can store either `SpecialisedTA` or `SpecialisedTB`,
    # and you don't pass any explicit disambiguator to `foo`
    foo(a.special, jsonNode)
    echo a    # => [a: 3, special: [abc: 5]]
    a.special = new SpecialisedTB
    foo(a.special, jsonNode)
    echo a    # => [a: 3, special: [def: 7]]
    
    
    Run

Reply via email to