3

In Vala I see that when I declare an array I have to specify the type, like

int[] myarray = { 1, 2, 3 };

I wonder if there is a way to have a mixed array like

smtg[] myarray = { 1, 'two', 3 };

I see that in this question they say that in C++ and C# it's not possible but I just started learning vala and I have no background with any C-like language so I want to be sure.

Community
  • 1
  • 1
wwr
  • 327
  • 1
  • 4
  • 11

1 Answers1

6

No.

That said, you can create an array of something that can hold other types, like GLib.Value or GLib.Variant, and Vala can automatically convert to/from those two, so you could do something like

GLib.Value[] values = {
  1,
  "two",
  3.0
}

It's usually a terrible idea (you're basically throwing away compile time type safety), but you can do it.

nemequ
  • 16,623
  • 1
  • 43
  • 62
  • The code gets compiled. Great ... but now ... how do I print such an array? I don't understand how I can set a type for the item in the foreach loop. http://pastebin.com/iZXpgQuK <- This is obviously wrong – wwr Feb 10 '16 at 00:27
  • 1
    I can't give a full answer in this little box, but basically you would need to do something like `foreach (GLib.Value value in values) { if (value.holds (typeof(int))) stdout.printf ("%d", (int) value); else if (value.holds (typeof(string))) stdout.printf ("%s", (string) value); } }`. You would probably also want to add some error checking in case it was a type you didn't expect. For GValue there is also a mechanism to transform from one type to another, and most simple types should have support for transforming to a string built in. See GLib.Value.type_transformable and transform. – nemequ Feb 10 '16 at 03:47