Hello again,
I have the following situation, with a myFoo variable of type Foo that is instantiated as one of the foo subtypes:
type
Foo = ref object of RootObj
x: string = "I'm Foo"
Bar1 = ref object of Foo
y: string = "I'm Bar1"
Bar2 = ref object of Foo
z: string = "I'm Bar2"
FooManager = ref object
myFoo: Foo
var manager: FooManager = FooManager(
myFoo: Bar1()
)
method showContents(b: Bar1) =
echo b.y
method showContents(b: Bar2) =
echo b.z
showContents(manager.myFoo)
That doesn't work because myFoo is a Foo type, not a Bar1 or Bar2 type, so I have to convert it by hand like so:
method showContents(f: Foo) =
if f of Bar1:
showContents(f.Bar1)
elif f of Bar2:
showContents(f.Bar2)
which defeats the point.
(I also tried using converters but couldn't make it work.)
Is there anyway to make this work without having to check the type of myFoo?
error message says: (line numbers are not the same as in your code)
/usercode/in.nim(21, 8) Warning: use {.base.} for base methods; baseless methods are deprecated [UseBase]
/usercode/in.nim(24, 8) Warning: use {.base.} for base methods; baseless methods are deprecated [UseBase]
/usercode/in.nim(27, 13) Error: type mismatch
Expression: showContents(manager.myFoo)
[1] manager.myFoo: Foo
Expected one of (first mismatch at [position]):
[1] method showContents(b: Bar1)
[1] method showContents(b: Bar2)
So following it I added a base method
type
Foo = ref object of RootObj
x: string = "I'm Foo"
Bar1 = ref object of Foo
y: string = "I'm Bar1"
Bar2 = ref object of Foo
z: string = "I'm Bar2"
FooManager = ref object
myFoo: Foo
var manager: FooManager = FooManager(
myFoo: Bar1()
)
method showContents(b: Foo) =
echo b.x
method showContents(b: Bar1) =
echo b.y
method showContents(b: Bar2) =
echo b.z
showContents(manager.myFoo)
works
I'm Bar1
You also need to provide a base "default" implementation for Foo like so:
method showContents(b: Foo) {.base.} =
raise newException(CatchableError, "Not implemented")
Can't believe I didn't think to do that :facepalm: The docs even had one like that but I assumed it wasn't needed for some reason.
Thank you both.