I am still struggling with the type system .
For instance:
type
A = ref object of RootObj
B = ref object of A
val:int
proc example*(x:seq[A]) =
for i in x:
echo repr i
var a:seq[A] = @[B(val:1), B(val:2)] #<--- This fails, but why?: Error:
type mismatch: got <seq[B]> but expected 'seq[A]'
echo repr a
example(a)
Run
On the other hand, the following works:
type
A = ref object of RootObj
B = ref object of A
val:int
proc example*(x:seq[A]) =
for i in x:
echo repr i
var a:seq[A] # I can create `seq[A]` like this. But why it failed like
a one liner?
a &= B(val:1)
a &= B(val:2)
echo repr a
example(a)
Run
Finally, the following fails:
type
A = ref object of RootObj
B = ref object of A
val:int
proc example*(x:seq[A]) =
for i in x:
echo repr i
var a:seq[B] # But `seq[A]` worked
a &= B(val:1)
a &= B(val:2)
echo repr a
example(a) # <-- Now this fails because I send `seq[B]` instead of
`seq[A]`.
Run
I got the same problem as in the first post:
Error: type mismatch: got <seq[B]>
but expected one of:
proc example(x: seq[A])
first type mismatch at position: 1
required type for x: seq[A]
but expression 'a' is of type: seq[B]
expression: example(a)