Skip to content

Latest commit

 

History

History
87 lines (71 loc) · 3.28 KB

README.md

File metadata and controls

87 lines (71 loc) · 3.28 KB

BabelFish License CircleCI Codacy Gitter

BabelFish is a dependency-free wrapper around JSR 223 that enables invoking other languages from Scala on the JVM.

Invoking JavaScript:

val eval = new Evaluator.JavaScript
eval("function sum(a, b) { return a + b; }")

val i = eval.as[Int]("sum(1, 2);")
assert(i + 3 == 6)

We can use Scala's Dynamic too to invoke:

val j: Int = eval.sum(9, 7)
assert(j == 16)

We can even invoke sum through a Scala trait:

trait Adder {
  def sum(a: Int, b: Int): Int
}
val adder: Adder = eval.as[Adder]
assert(adder.sum(7, 8) == 15)

Note that we can invoke sum for other types too:

assert(eval.sum[String]("hello", "world") == "helloworld")
eval.sum[Int]("hello", "world") // Exception!

Support for objects:

val eval = new Evaluator.JavaScript
val rick = eval(s"""
  new function () {
    this.name = "Rick";
    this.age = 28;
    this.sayHi = function (friend) {
      return "Hello " + friend + "! My name is " + this.name;
    }
  };
""")
assert(rick.sayHi[String]("Anna") == "Hello Anna! My name is Rick")
assert(rick.age[Int] == 28)

We can even eval script files:

val eval = new Evaluator.JavaScript
val $ = eval.file("scripts/lodash.min.js")
assert($.min[Int](Array(48, 12, 19, 23)) == 12)

See the tests for more examples. codecov