1

I would like to work in Ceylon with a multidimensional array. Is this planned in Ceylon? If so, how can I declare it?

I would like to use this construct in Ceylon, as shown here in Java:

int x = 5;
int y = 5;

String[][] myStringArray = new String [x][y];

myStringArray[2][2] = "a string";
Martin
  • 11
  • 2

2 Answers2

3

First, consider whether you really need an array (i.e. something with fixed length and modifiable elements), or whether a list (or list of lists) or a map might be better. Though from your example, you seem to need modification.

In the JVM, a "multidimensional" array is just an array of arrays.

In Java, new String[y] creates an array filled with null entries, which is not an allowed value of type String in Ceylon. So you can either have an array of String? (which allows null), or pre-fill your array with some other value, using e.g. Array.ofSize(...):

Array.ofSize(y, "hello")

The same is valid for arrays of arrays. We could do this:

value myStringArray = Array.ofSize(x, Array.ofSize(y, "hello"));

Though this would have the same array in each "row" of the 2D-array, which is not what we want (as replacing myStringArray[2][2] would replace all entries with a 2 as the second coordinate). Here the other Array constructor is useful, which takes an iterable:

value myStringArray = Array({ Array.ofSize(y, "hello") }.repeat(x));

This takes advantage of the fact that the iterable enumeration evaluates its arguments lazily, and thus the array constructor will get x different elements.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
1

I like Paulo's answer, but here's an alternative approach, which allows us to use a comprehension to populate the 2D array:

//the size of the square 2D array
value n = 5;

//create it using a nested comprehension
value arr = Array { 
    for (i in 1..n-1) Array { 
        for (j in 0..n-1) 
            i==j then 1 else 0 
    }
};

//display it
for (row in arr) {
    printAll(row);
}
Gavin King
  • 3,182
  • 1
  • 13
  • 11