Hello
This is my sample:
type
X1* = object of RootObj
X2* = object of X1
let s: seq[X1] = @[X2()]
and I get this: type mismatch: got 'seq[X2]' for '@[X2()]' but expected 'seq[X1]'
Is it supported in some other way or at all?
I modified it thinking it's just some forced inference(ye):
type
X1* = object of RootObj
X2* = object of X1
X3* = object of X1
let s: seq[X1] = @[X2(), X3()]
and now it fails at runtime: Error: unhandled exception: invalid object assignment [ObjectAssignmentDefect]
But it works with ref and that makes sense.
Nim's stack based OOP is mostly just for inheriting procedures and fields, it does not allow storing multiple types in a single collection or anything else that general OOP does. If you wanted to store multiple types in a single collection you could write something like the following:
type
X1* = object of RootObj
X2* = object of X1
method doThing(x1: X1) {.base.} = echo "X1"
method doThing(x2: X2) = echo "X2"
proc toBase[T: X1](x: T): X1 =
static: assert sizeof(x) == sizeof(X1)
copyMem(result.addr, x.unsafeAddr, sizeof(x))
let s = @[X2().toBase, X1(), X2().toBase]
for i in s:
i.doThing()
It is highly suggested though that if you want to use Nim's OOP mechanisms you use ref.