In Scala.JS is there a call to get the platform I'm running on? - scala.js

I have some Scala code for a library which I compile for both the JVM and ScalaJS.
Right now I have a "pure" project, without special code in the js and jvm proojects, and I'd like to keep it that way due to intellij integration and some other factors.
However, I do have a small bit of code (1-2 lines) that needs to change based on whether I'm in the JVM or JS. I'd like an easy way to accomplish this that doesn't require me changing my whole project structure.
Basically I'd like a call "isJS" that returns true if I'm on JavaScript and false otherwise.

There is nothing standard, as it would require to extend the API available on the JVM, which Scala.js cannot do.
You can build it yourself easily with a tiny object Platform with two different implementations in the js/ and jvm/ subprojects. For example for JS it would be:
object Platform {
final val isJS = true
final val isJVM = false
}
Of course that requires to be non-pure. You could also abstract that in a tiny library offering only that feature. That is what the platform project of catalysts does, for example.
If you want to keep completely pure and no dependency, you have to resort to a hack:
val isJS = 1.0.toString == "1"
This works because, on the JVM, 1.0.toString returns "1.0", but on JS it returns "1".

You can do:
val isJS = System.getProperty("java.vm.name") == "Scala.js"

Related

How to easily play around with the classes in an Scala/SBT project?

I'm new to Scala/SBT and I'm having trouble understanding how to just try out the classes and functions of a package to see what they're about, to get a feel for them. For example, take https://github.com/plokhotnyuk/rtree2d . What I want to do is something like (in the top level folder of the project)
# sbt
> console
> import com.github.plokhotnyuk.rtree2d.core._
...
etc. But this won't work as it can't find the import even though this is in the project. I apologize for the vague question, though I hope from my hand-waving it's clear what I want to do. Another way to put it maybe, is that I'm looking for something like the intuitive ease of use which I've come to take for granted in Python -- using just bash and the interpreter. As a last resort I can create a separate project and import this package and write a Main object but this seems much too roundabout and cumbersome for what I want to do. I'd also like if possible to avoid IDEs, since I never really feel in control with them as they do all sorts of things behind the scenes in the background adding a lot of bulk and complexity.
rtree2d takes advantage of sbt's multi-module capabilities; a common use for this is to put the core functionality in a module and have less core aspects (e.g. higher-level APIs or integrations with other projects) in modules which depend on the core: all of these modules can be published independently and have their own dependencies.
This can be seen in the build.sbt file:
// The main project -- LR
lazy val rtree2d = project.in(file("."))
.aggregate(`rtree2d-coreJVM`, `rtree2d-coreJS`, `rtree2d-benchmark`)
// details omitted --LR
// Defines the basic skeleton for the core JVM and JS projects --LR
lazy val `rtree2d-core` = crossProject(JVMPlatform, JSPlatform)
// details omitted
// Turns the skeleton into the core JVM project --LR
lazy val `rtree2d-coreJVM` = `rtree2d-core`.jvm
// Turns the skeleton into the core JS project --LR
lazy val `rtree2d-coreJS` = `rtree2d-core`.js
lazy val `rtree2d-benchmark` = project
In sbt, commands can be scoped to particular modules with module/command, so in the interactive sbt shell (from the top-level), you can do
> rtree2d-coreJVM/console
to run the console within the JVM core module. You could also run sbt 'rtree2d-coreJVM/console' directly from the shell in the top level, though this may require some care around shell quoting etc.

Scala template engine for creating js files

I want to create js files using a template engine with Scala. Is it possible with the popular templating engines for Scala, namely Play and Scalate? If possible, than what are the pros and cons for using either of them?
Just create view with .js ext, i.e.: app/views/myScript.scala.js and dummy content:
#(message: String)
alert("#message");
Then add an action into your controller:
def myScript = Action {
// use views.js... NOT views.html... !
Ok(views.js.myScript.render("Whoha! I'm dynamic JS in Scala :)"))
}
or in Java version:
public Result myScript(){
// use views.js... NOT views.html... !
return ok(views.js.myScript.render("Yey! I'm dynamic JS in Java :)"));
}
Add the route to this action:
GET /my-script controllers.Application.myScript()
So you can use this route directly:
<script src="/my-script"></script>
note, that Play should return valid Content-Type:text/javascript; charset=utf-8 in the response, anyway depending on version you are using it may be required to enforce this manually within your action (use browser's inspection tool to check the response type)
It really depends on what you want to achieve, i.e. how sophisticated your JavaScript code will be, but, unless it's something really small and simple, I'd suggest using the Scala.js. This way you basically will write some Scala code that will compile into JavaScript, and that compiled JavaScript you should be able to include into your Play application.
Advantages of writing Scala vs JavaScript should be pretty obvious (type safety, using lots of the existing Scala libraries). Disadvantage would be some delays for Scala -> JavaScript compilation, and also lack of the same seamless integration of Scala.js and Play, like Play has with its own templating engine. It's up to you to decide if the extra work to make these 2 work together worth it.

Typesafe config programmatic modification and persistence

Typesafe Config documentation and library examples make a point that type safety can be achieved by making a configuration object or nested objects with getter methods mapped to Config.getType(key) methods.
If I wrap config calls in something like this:
class MyConfig (cfg:Config) {
val language = cfg.getString("app.language")
val database = new {
val url = cfg.getString("db.url")
val port = cfg.getInt("db.port")
...
}
}
I can do decent looking calls like config.database.url. Neat. (That dot looks so much greater than underscore)
What I don't quite get is how to allow modifying properties and saving them - quoting documentation, config is immutable. My attempts so far turned into either a gross spaghetti (closures with var config) or horrendous boilerplate (modifying a plain object and creating a new config from it to save), so I turned here for help.
I'd appreciate if someone showed me a good pattern for programmatically modifiable configuration using Typesafe Config.
It is possible that Typesafe Config just isn't a right tool for the job. I have little use for it's powerful merging and inheritance capabilities, instead I mostly need a simple, concise, unicode-friendly and type-safe way to load and store properties. I already do have one, a reflection-based java lib working with annotated POJOs. Doesn't seem to be a lot of variety with configuration libraries in Scala. I may have been too eager to throw away my trusty java tools.

Build Scala against different versions of external API

I'm writing a small library which I'd like to be backwards compatible with older versions of an API, yet use features of the latest API when possible.
So for example, I have a project which uses an external API, which I'll call FooFoo_v1.
Initially, my code looked like this:
// in Widget.scala
val f = new Foo
f.bar
Foo has since released a new version of their API, FooFoo_v2, which adds the bat method. So long as I'm compiling against the new version, this works fine:
// in Widget.scala
val f = new Foo
f.bar
f.bat
But if you try to build against FooFoo_v1, the build obviously fails. Since the bat feature is truly optional, and I'd like to allow folks to build my code against FooFoo_v1 or FooFoo_v2.
Ignoring the details of the dependency management, what's the right high level approach for something like this? My aim is to keep it as simple as possible.
I think you should split your library in two pieces - one with features used from FooFoo_v1, another depending on the first one and on FooFoo_v2 and using features from FooFoo_v2. How to accomplish it depends on your code... If it's too difficult it's better to follow #rex-kerr advice - to maintain two branches.
I would simply keep separate branches of the project in a repository (one which is sufficiently robust to allow you to edit one and merge effortlessly into the others--git would be my first choice).
If you must do the selection at runtime, then you're limited to using reflection for any new methods.

Why is it faster to call external scala compiler than use the runtime interpreter library?

Why is it faster to call external scala compiler than use the runtime interpreter library?
In the code below it takes almost 2s to warm up the interpreter.
val out = new PrintStream(new FileOutputStream("/dev/null"))
val flusher = new java.io.PrintWriter(out)
val interpret = {
val settings = new scala.tools.nsc.GenericRunnerSettings(println _)
settings.usejavacp.value = true
new scala.tools.nsc.interpreter.IMain(settings, flusher)
}
interpret.interpret(" ") // <-- warming up
interpret.interpret(" Hello World ")
In the other hand, when running Scala compiler from command line like in a shell session:
scala HelloWorld.scala
it takes less than 0.5s to print a Hello World.
I am trying to parse+execute some Java, Scala or similar code given in a string during runtime (it is a script interpreter, i.e. it will be run only one time during my app execution).
Scala code would be better obviously, but only if it can be as fast as the Java option.
Is there any faster alternative than nsc.interpreter and external compiler to execute code from a string at runtime?
The best I could found was Janino; it is faster than Scala compiler and does not require the JDK (a very interesting feature).
As a last resource, how fast are Java Scripting Engines compared to a reflected or bytecode-compiled Java code? I found that, at least, they can be compiled: Compiling oft-used scripts.
Chosen solution:
runtimecompilescala.
There are many things left unstated (like memory settings), but you're comparing apples and oranges.
The command-line script runner is not a REPL session; instead, it wraps your code in a simple object with a main method, compiles and runs that.
By contrast, each interpreted line (or compilable thing) in the REPL is wrapped in an object (with the session history imported so you can refer to past results).
Even modulo REPL start-up, this has performance consequences, see this issue.
The simple wrap-it logic for the script runner is built into the parser. Here is how the script runner runs the compilation. Or, it looks like this is how -e is handled.
Edit: your comment to your question implies that you really want fsc compile server behavior. Fire up fsc and use the compile client.