I'm seeming to be having problems with the type system and object inheritance. First, here's the code and I'll explain what I am trying to do.
type
Object = ref object of RootObj
name, desc: string
collectable: bool
Container = ref object of Object
contents: seq[Object]
proc newContainer(name="", desc="", collectable=false, contents=newSeq[Object](0)): Container =
return Container(name:name, desc:desc, collectable:collectable, contents:contents)
#Raises an error: "Type mistmatch: got <contents seq[Container]>
discard newContainer(contents= @[newContainer()])
In short, I would like the object type Container to be recursive in that the contents field could take either another container, or a regular object. I've done other little code snippets like this and they've seemed to work- so I am unsure why exactly Nim complains about this in particular. The only solution I see at this time is to wrap the two types into a single one as an object variant. But is there a way to get around that? Thanks for your time.The compiler infers the type of @[newContainer()] to be seq[Container], which does not conform to @seq[Object] (covariance).
To make the type of an array or sequence explicit, cast the first element, e.g.:
discard newContainer(contents= @[Object newContainer()])