Skip to content

pathikrit/BabelFish

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Invoke other languages from Scala on the JVM

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages