classtclreturn-valueitcl

How to treat a return value from method as a class type - Itcl


Suppose I have the following code implemented in Itcl.

package require Itcl

itcl::class A {
    constructor {} { puts $this }
    destructor {}
    public method Print {} { puts "ok" }
}

itcl::class B {
    constructor {} { }
    destructor {}
    public method returnA {} { return [A #auto] }
}

B b   ;# create an instance of class B
set obj [b returnA]   ; #assign return value to obj
$obj Print    ;# should treat obj as an A type and print ok

Now, I get the following error:
invalid command name "0" while executing "$obj Print"

I understood that I need to add scopes to my variable or to the Print command in order to invoke Print method that associated to class A. But I don't really know how.

I also read the following post:

How to get a reference on the Itcl class member variable?

But it doesn't says there how to treat the return value as a specific class type variable


Solution

  • You have to qualify the name of the yet to be created instance of class A:

    A [namespace current]::#auto
    

    Otherwise, the name of the created object is returned in an unqualified manner (0, a0, ...), which cannot be resolved to a Tcl command for the scope of the caller of returnA.