John February 2016

Xtend: Add element to array in for-loop

I am trying to do the simplest operation in Xtend, but don't know how. I want to add an double value to an double[] array inside a for-loop.

For example:

def do(EList<MyObject> list) {
    var double[] array = newDoubleArrayOfSize(list.size);
    for (i : 0 ..< list.size) {
        array[i] = list.get(i).myValue;
    }
    return array;
}

The forth line shows an error, because I can't use array[i] = ....

How do I implement that in Xtend? Haven't found anything in the user guide.

Answers


snorbi February 2016

Xtend has a different ("list-like") syntax for accessing array elements, see the related documentation for details:

Retrieving and setting values of arrays is done through the extension methods get(int) and set(int, T) which are specifically overloaded for arrays and are translated directly to the equivalent native Java code myArray[int].

So your code should be:

def method(EList<MyObject> list) {
    var double[] array = newDoubleArrayOfSize(list.size);
    for (i : 0 ..< list.size) {
        array.set(i, list.get(i).myValue);
    }
    return array;
}

You can further simplify your method by omitting semicolons and the type declaration of the array variable:

def method(EList<MyObject> list) {
    val array = newDoubleArrayOfSize(list.size)
    for (i : 0 ..< list.size) {
        array.set(i, list.get(i).myValue)
    }
    return array
}

Another alternative is to write your method in a more functional style. If you can replace EList with List (or EList extends/implements List) then you could simply write:

def double[] method(List<MyObject> list) {
    list.map[myValue]
}

In this case you must explicitly declare the return type as double[] because otherwise it would be inferred as List<Double>.

(Just one more thing: usually collections are preferred over arrays because they are more flexible and have more rich APIs, and Xtend has some additional goodies as well like collection literals.)

Post Status

Asked in February 2016
Viewed 1,208 times
Voted 14
Answered 1 times

Search




Leave an answer