Stephen Maina
Stephen Maina

Reputation: 21

Java type is unknown in js side

Please help point out what the problem might be in the code below. I have this javascript code (in a file '/arithmetic.js') which I'm testing using GraalVM's Context in java

function sum(num, b) {
    return num.add(b)
}

function diff(num, b) {
    return num.sub(b)
}

The java side looks like this

public class Num {

    final int a;

    public Num(int a) {
        this.a = a;
    }

    public int add(int b) {
        return this.a + b;
    }

    public int sub(int b) {
        return this.a - b;
    }
}

In the main class, I have

Engine engine = Engine.create();
try (Context context = Context.newBuilder().engine(engine).build()) {
    context.eval(Source.newBuilder("js", loadFile("/arithmetic.js"), "arithmetic").build());
    Num ten = new Num(10);
    System.out.printf("10 + 3 = %d%n", ten.add(3)); //<-- just checking

    context.getBindings("js").putMember("num", ten); //<-- is this line even necessary?
    Value getSum = context.getBindings("js").getMember("sum");
    Value result = getSum.execute(ten, 20);
    System.out.println(result.asInt());
}

I get the output below:

> Task :graalvm-js-app:SampleJs.main() FAILED
10 + 3 = 13
Exception in thread "main" TypeError: invokeMember (add) on example.Num@31e4bb20 failed due to: Unknown identifier: add
    at <js> sum(arithmetic:2:34-43)

Upvotes: 1

Views: 263

Answers (1)

Stephen Maina
Stephen Maina

Reputation: 21

In this particular case, it appears that I needed just one slight tweak when building the context. It's not so obvious but it kinda makes sense in the context of the problem encountered

Context.newBuilder().engine(engine).allowAllAccess(true).build()

Upvotes: 1

Related Questions