Hello World! *

What’s the first thing that we usually do when we start learning a programming language? That’s it, a ‘Hello World’. In order to implement it in Scala, we first need to know two basics:

  • How can we make executable applications?

Easy! We just need an object that inherits from App. The reserved word object is used to define an object. The reserved word extends is used to implement inheritance.

  • How can we print a message on the screen?

We might want to use a brief and easy-to-type name such as System.out.println, but unfortunately we have to be content with println function.

So, now that we have our two main ingredients, let’s go with it:


object HelloWorld extends App {

  println("Hello World!")

}

Ok… and now, how do I run it?

The first thing to be done is to add an extension to our wonderful first source file. Unexpectedly, in a display of unparalleled originality, the extension of Scala source files is .scala.

Once we have the source file, we need some tools to work with it. The first option to build and run Scala code is SBT (Simple Build Tool). It is similar to Maven or Ant. It allows us to add dependencies and set the Scala version we want to work with. Some IDEs such as Intellij use it as a built in.

How to install SBT?

Which are the basic SBT commands?

  • compile: compiles the source files in a project.
  • test:compile: compiles the tests in a project. If necessary, it will compile the source files too.
  • run: runs an application. If necessary, it will compile the source files.
  • test: runs the tests in a project. If necessary, it will compile the source files and the tests.

To execute our ‘Hello world’, we just launch sbt in the directory where the source file .scala is and we write the command ’run’.

Now we wait

e4tvwy

Hello, someone there?

If it’s the first time you use Scala, SBT will try to get all the required dependencies to build and run Scala code. It may take a while, depending on your Internet connection. This won’t happen next time, just the first one.

Et voila! First program in Scala. Easy-peasy, isn’t it?

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s