Search code examples
javagroovygraalvmpolyglot

How to use Graalvm's Truffle framework with Groovy?


The Graalvm jdk uses the Truffle framework to call functions and receive objects from other languages, such as R, Python, Ruby and Javascript. How can I use it from Groovy? Can I call it's APIs using Groovy code? Or do I have to call the Truffle APIs using Java code and then call this Java code from Groovy?


Solution

  • You are probably not interested in Truffle API, which is API for the development of new Truffle based languages, but in Graal SDK: API for embedding Truffle languages into Java applications. I guess you can use that API from Groovy like you would use any other Java API.

    Some resources:

    https://www.graalvm.org/docs/reference-manual/embed/

    https://www.graalvm.org/sdk/javadoc/index.html?org/graalvm/polyglot/Context.html

    TL;DR example in Java:

    import org.graalvm.polyglot.*;
    import org.graalvm.polyglot.proxy.*;
    
    public class HelloPolyglot {
        public static void main(String[] args) {
            System.out.println("Hello Java!");
            try (Context context = Context.create()) {
                context.eval("js", "print('Hello JavaScript!');");
            }
        }
    }