Scala for Node.js developers — Step 3: Hello world

In last post I described what structure is expected (and will be created partly) by sbt. This time let’s write “hello world”.

This post assumes that you are starting with the code listed here.

Create a file called Main.scala in src/main/scala and put following inside:

package Main
object Main extends App {
println("Hello, world!")
  def mul(x: Int, y: Int):Int = x * y
}

Ignore mul function for a second, overall it’s and object that when it get’s defined (when you run the code) prints “Hello, world!”. To check it out — run sbt run in main directory of your project — you should see following:

~/projects/myFirstScalaProject$ sbt run
[info] Loading global plugins from /home/kamil/.sbt/0.13/plugins
[info] Set current project to myFirstScalaProject (in build file:/home/kamil/projects/myFirstScalaProject/)
[info] Compiling 1 Scala source to /home/kamil/projects/myFirstScalaProject/target/scala-2.12/classes...
[info] Running Main.Main
Hello, world!
[success] Total time: 9 s, completed 05-Apr-2017 15:14:38

Well done. Code work. Here’s explanation what you just wrote:

You create an object Main inside package Main. It’s a singleton object. In Scala you don’t need to export neither classes nor objects — anything that you will define it’s already available outside the file referred by ${package}.${object/class}. Defining a (singleton) object in Scala is equivalent to exporting new instance of class in Node.js:

module.exports = new MyClassDefinedAbove(whatever, parameters)

You can think about it in the following way: as program loads, it loads all classes and objects available, to load object it need to execute everything inside brackets {} and because of that when running sbt run you are getting “Hello, World!” printed.

I dropped a bonus as it would be nice/necessary to test something as now you wrote your first code. In Main object there’s this line:

def mul(x: Int, y: Int):Int = x * y

You can translate this(and whole object) to Node.js(6+) in following way:

class Main {
  constructor() {
console.log("Hello, World!")
}
  mul(x, y) {
return x * y
}
}
module.exports = new Main();

Some details are non-transferable like mul method in Scala version checks the type of passed variables (both needs to be integers) and guarantees that output will be integer as well — this args and result type checking is done on compilation which is a nice layer of safety that you aren’t doing anything silly like adding boolean and number.

Second interesting fact is that Scala doesn’t have a return statement — every function returns last statement result.

Ok. I will let you go now, we will test it in the next post :)