xtend

cannot convert from Iterable<Iterable<Integer>> to int[][]


When I print

(0..1).map[i | (0..1).map[j | j]]

I get [[0, 1], [0, 1]] as output.

But when I want to assign it to a 2d int array

val int[][] mat = (1..2).map[i | (1..2).map[j | i * j]]

I get the error message

Type mismatch: cannot convert from Iterable<Iterable> to int[][]

How can I convert to int[][] or what is the better way to initialize the 2d array?


Solution

  • Handling primitives and arrays often feels a bit weird in Xtend, but to my surprise there is actually a quite simple solution using the com.google.common.primitives.Ints class from Guava:

    val int[][] intArr = (0 .. 1).map[Ints.toArray((0 .. 1).toList)]
    

    This relies on Xtend's automatic conversion between arrays and list, which also works with multidimensional arrays - and as in this case it apparently can convert Iterable<int[]> to int[][].

    If you only want to create a small, constant int[][] array, then you could also use list literals instead:

    val int[][] intArr = #[#[0, 1], #[0, 1]]
    

    If you only want to create an empty int[][] array, you can just use newIntArrayOfSize(s1, s2):

    val int[][] emptyIntArr  = newIntArrayOfSize(2, 2)