Hi I'm trying to get interitance to work with some methods that use 'var' arguments. Here is a complete (but simplified) example that outlines my issue:
type
BaseType = ref object of RootObj
message: string
InheritedType = ref object of BaseType
otherprop: int
method thisFunctionDoesntWork(obj: var BaseType) {.base.} =
echo obj.message
obj.message = obj.message & " has already been echoed."
method thisFunctionWorks(obj: BaseType) {.base.} =
echo obj.message
var base = BaseType(
message: "This is the base type."
)
var inherited = InheritedType(
message: "This is the inherited type.",
otherprop: 10
)
thisFunctionWorks(base) # OK
thisFunctionWorks(inherited) # OK
thisFunctionDoesntWork(base) #OK
thisFunctionDoesntWork(inherited) #ERROR
issue.nim(28, 23) Error: type mismatch: got <InheritedType> but expected one of: method thisFunctionDoesntWork(obj: var BaseType) first type mismatch at position: 1 required type for obj: var BaseType but expression 'inherited' is of type: InheritedType expression: thisFunctionDoesntWork(inherited) --
What do I need to do to get this to work?
Thanks.
The type of inherited is InheritedType. If this worked, then thisFunctionDoesntWork could set the variable to a BaseType, which would break type safety.
This works:
var inherited: BaseType = InheritedType(...)
What do I need
Just remove the var in "(obj: var BaseType)" I bet you do not need and want it. For ref types you can modify the fields without var.
Just remove the var in "(obj: var BaseType)" I bet you do not need and want it.
After reading that I got all high and mighty "Of course I need it!!!!", I thought to myself.
And then I read this:
For ref types you can modify the fields without var.
Oh... yeah..... right... That's all I want to do. You're right, I don't need 'var'.
Perfect solution. Thank you.
It also made @xigoi's comment make more sense, I can see the type safety issue now. Thank you.