You could try assign subclass instances to arrays of it's parent class, as shown in the snippet bellow.
It is not a very elegant syntax, but at least it makes your plus(A arg[]) function work like you would expect.

best,
Casper

class A {
    42 => int a;

    

    fun void print() {
        <<<a>>>;
    }
}

class B extends A {
    101 => int b;

    

    fun void print() {
        <<<b>>>;
    }
}

fun void plus(A arg[]) {
    for (0 => int i; i <  arg.size()     ; i++) {
        arg[i].a ++;
        arg[i].print();
    }

    

}

// first declare the 'container'.
A @ foo[2];

// use new operator to create B instances.
(new B) @=> foo[0];
(new B) @=> foo[1];

1 => foo[0].a;
2 => foo[1].a;


plus(foo);
// notice, foo[0] & foo[1] still behave like a B instance.
<<<"foo[0].a", foo[0].a>>>;
<<<"foo[1].a", foo[1].a>>>;



  1. Inheritance and Arrays (Julien Saint-Martin)

From: Julien Saint-Martin <julien.saintmartin@googlemail.com>
To: chuck-users@lists.cs.princeton.edu
Date: 2 januari 2015 16:15:54 CET
Reply-To: ChucK Users Mailing List <chuck-users@lists.cs.princeton.edu>
Subject: [chuck-users] Inheritance and Arrays


Hi!

I would like to pass arrays of objects to a function taking an array of parent class as argument.
I try different things but unfortunately I have compilation errors each time.

The following example works with no array:

class A {
       int a;
}

class B extends A {
int b;
}

fun void plus(A arg) {
       arg.a ++;
}

B foo;

1 => foo.a;
plus (foo);
<<<"foo.a", foo.a>>>;




But When I try the same with arrays it doesn't compile:
[l13.ck]:line(22): argument type(s) do not match:
[l13.ck]:line(22): ... for function 'plus(...)' ...
[l13.ck]:line(22): ...(please check the argument types)

class A {
       int a;
}

class B extends A {
int b;
}

fun void plus(A arg[]) {
       for (0 => int i; i <  arg.size()     ; i++) {
       arg[i].a ++;
       }

}

B foo[2];

1 => foo[0].a;
2 => foo[1].a;
plus (foo);
<<<"foo[0].a", foo[0].a>>>;
<<<"foo[1].a", foo[1].a>>>;


Any idea ?

Thanks in advance and Happy new year!!

Julien




_______________________________________________
chuck-users mailing list
chuck-users@lists.cs.princeton.edu
https://lists.cs.princeton.edu/mailman/listinfo/chuck-users