very simple example code here. It returns that value if the argument is an even
number, and returns the string "odd" if the argument is odd.
proc hoge(x: int): int|string =
if x mod 2 == 0:
return x
return "odd"
Run
compile error
(4, 12) Error: type mismatch: got <string> but expected 'int'
Run
What I really want to do is a bit more complicated. I want to define a method
that returns different objects by conditional branching using case..of.
type
A = ref object of RootObj
name: string
value: string
B = ref object of RootObj
name: string
type C = ref object of RootObj
flg: string
proc parseStatement(self: C): A|B =
case self.flg
of "A":
return A(name: "a", value: "val")
of "B":
return B(name: "b")
else:
null
let c = C(flg: "a")
c.parseStatement()
Run
If this is TypeScript, I can think of two solutions. The first one is to define
the interface. The second one is to use Union types.
If you use the interface, it will be as follows.
// TypeScript
interface Hoge {
name: string;
}
class A implements Hoge {
public value: string;
constructor(public name: string, value: string) {
this.value = value;
}
}
class B implements Hoge {
constructor(public name: string) {}
}
class C {
constructor(public flg: string) {}
hoge(): Hoge { // here!!!
switch (this.flg) {
case 'A':
return new A('A', 'val');
case 'B':
return new B('B');
default:
return null;
}
}
}
Run
It is easier to use Union types, even if you do not define an interface, you
can write like this.
// TypeScript
class C {
constructor(public flg: string) {}
hoge(): A | B { // here!!!
switch (this.flg) {
case 'A':
return new A('A', 'val');
case 'B':
return new B('B');
default:
return null;
}
}
}
Run
What I'd like to ask is how to solve this problem. In the case of Nim, I think
that we will use concept rather than interface. Actually, any method can be
used as long as it can be solved, but if you have enough capacity to show Nim
better, please suggest multiple solutions.
I read the document about concept, but it was abstract and I could not
understand well. I would be happy if you could write simple code as a concrete
example.
Thanks you for your time.