Jason Washo
Jason Washo

Reputation: 625

JsInterop - Get Value in Array

I created my own custom array in JsInterop:

@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Array")
public interface Array<T> 
{
    public void push(T value);

    @JsProperty(name = "length")
    public int getLength();

    @JsProperty(name = "length")
    void setLength(int newLength);

    @JsOverlay
    default T get(int index) {
        return JsArrayHelper.getArrayValue(this, index);
    }
}

And here is the JsArrayHelper class scaled down:

public class JsArrayHelper 
{
    //TODO: Eliminate JSNI. Better way to do this?
    public static native <T> T getArrayValue(Array<T> a, int i) /*-{
        return a[i];
    }-*/;
}

Is there a better way to get the value of the array instead of using JSNI?

Upvotes: 2

Views: 466

Answers (1)

Ignacio Baca
Ignacio Baca

Reputation: 1578

Use com.google.jsinterop:base lib, this lib should include utilities for anything that cannot be done with JsInterop, and the lib will maintain compatibility with GWT and j2cl. The lib is pretty small (only 10 classes, 2 of them internal), so just add it to your project and explore all its utilities.

So instead of your custom Array<T>.get(int) and JsArrayHelper classes use jsinterop.base.JsArrayLike<T>.getAt(int).

Upvotes: 4

Related Questions