How do I create Array<Dynamic> literals?

In haxe, [1, 2, 3] creates an array. All the members must be of the same type. If you want to create an array where the elements are of different types, you need to explicitly tell the compiler that it’s an Array<Dynamic>. The [example in the documentation](https://haxe.org/manual/std-Array.html) suggests this:

var myExplicitArray: Array<Dynamic> = [10, "Sally", true];

But that defines a new variable. What do I do if I want to use the array, as a literal, in some other structure? Such as, in my case, creating a large, complex JSON structure?

Or, in other words, how do I do this:

doSomethingWithJson([1, ["value" => 2], "three"]);

(As an aside, the same problem applies with mixed-type maps.)

(I also posted this to SO here, but it’s not getting any love: https://stackoverflow.com/questions/79873319/how-do-i-represent-an-arraydynamic-literal-in-haxe Feel free to answer there if you want some cheap karma…)

In your example, I believe you could do something like:

doSomethingWithJson(([1, ["value" => 2], "three"] : Array<Dynamic>));

A colon can be used after a literal to specify its type in-place, though it often has to be surrounded by parentheses for whatever reason.

I’m fairly new to the language, so I’m sure someone with more experience here can offer more insight.

In most cases when dealing with json you are passing objects as Dynamic which works fine with arrays of mixed types, for example this signature works fine as-is with your original example:

function doSomethingWithJson(obj:Dynamic) { /*...*/ }

function main() {
    doSomethingWithJson([1, ["value" => 2], "three"]);
}

The reason is that the parentheses are part of the syntax: ( expr : Type ), see: type check - Haxe - The Cross-platform Toolkit

1 Like

That’s only because it’s a simple example, though. Consider this:

		doSomethingWithJson([1 => [1, ["value" => 2], "three"]]);

Casting the array does work, although it’s a bit ugly. And I can avoid some of the issues by using JSON structure syntax, like {"one": 1, "two": “two”}, as that creates a structure rather than a map; JsonPrinter doesn’t seem to care. Is there a similar shortcut for mixed-type arrays? Having to cast everywhere isn’t great for complex literals intended to go to JSON APIs.

If the first element of the array is Dynamic, Haxe will infer the rest as Dynamic too. In most cases, you can save even more space by using Any.

[1 => [(1:Any), ["value" => 2], "three"]]