Is it possible to compile (transpile) Scala to the browser, keeping the ability to interpret Scala code provided dynamically by the user?

Viewed 224

I know that Scala.js can transpile to JS, but it doesn't support reflection. Is there any way to interpret user-provided Scala code without recurring to the server side?

If interpreting Scala in this way is not possible, is it possible to run a user-provided JavaScript code from the Scala code (i.e. from that Scala code that will be transpiled)?

2 Answers

To the first question: no, that is not possible. The Scala compiler cannot be compiled to JavaScript, for a number of reasons, which makes it impossible to compile user-provided code in the browser.

To the second question: yes, with js.eval(dynamicJSCodeString). Standard warnings about eval and security apply.

To the first question: yes, that is definitely possible. You just need to write a Scala interpreter either in ECMAScript or in a language for which a compiler to ECMAScript exists (e.g. TypeScript, CoffeeScript, Python, Ruby, Kotlin, or of course Scala), or in a language for which an interpreter exists that is written either in ECMAScript or in a language for which a compiler to ECMAScript exists … and of course you can chain those approaches as well.

Related