Getting start with Scala

In this post we will introduce Scala programming language. Also we will learn how to install it and create a famous Hello World application.

Scala as it’s own site says, is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothy integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.

The name Scala stands for “scalable language”. You can use Scala to a wide range of programing tasks, from writing small scripts to building large systems.

Scala runs on the standard Java platform and interoperates seamlessly with all Java libraries.

Technically, Scala is a blend of object-oriented and functional programing concepts in a statically typed language.

Scala is expressive & light-weight

var capitals = Map (
  "Brazil" -> "Brasilia",
  "US" -> "Washington",
  "France" -> "Paris"
capitals += ("Japan" -> "Tokio")

Everything is an object

Scala is a pure object-oriented language in the sense that everything is an object, including numbers or functions.

Numbers are objects

Since numbers are objects, they also have methods. And in fact, an arithmetic operations + – * / consists exclusively of method calls.

This expression:

1 + 2 * 3 / x

Is equivalent to the following:


Functions are objects

Functions are also object in Scala. It’s possible to pass functions as arguments, to store them in variables, and return them from other functions. This ability to manipulate functions as values is one of the cornerstone of a very interesting programming paradigm called functional programming.

See the code example:

object Timer {
  def oncePerSecond(callback: () => Unit) {
    while (true) { callback(); Thread sleep 1000 }
  def timeFlies() {
    println("time flies like an arrow")

  def main(args: Array[String]) {


Classes in Scala are declared using a syntax which is close to Javaś syntax. One important different is that classes in Scala can have parameters:

class Complex(real: Double, imaginary: Double) {
  def re() = real
  def im() = imaginary

This class takes two arguments. These arguments must be passed when creating an instanceof class Complex, as follow: new Complex(1.5, 2.3). Also the class contains two methods, called re and im, which give access to these two parts.

Inheritance and overriding

All classes in Scala inherit from a super-class. Whem no super-class is specified, scala.AnyRef is implicity used.

It is possible to override methods inherited from a super-class. It is however mandatory to explicity specify that a method overrides another one using the override modified:

class Complex(real: Double, imaginary: Double) {
  def re = real
  def im = imaginary

  override def toString() =
    "" + re + (if (im < 0) "" else "+") + im + "i"


Apart from inheriting code from a super-class, a Scala class can also import code from one or server traits.

The easiest wary to understand what traits are is to view them as interfaces which can also contains code. When a class inherits froma trait, it implements the trait’s interface, and inherits all the code contained in the trait.

Let’s look a classical example: ordered object. It is often useful to be able to compare objects of a given class among themselves, for example to sort them. In Java, object which are comparable implement the Comparable interface. In Scala, we can do a bit better by defining our equivalent of Comparable as a trait:

trait Ord {
  def <  (that: Any): Boolean
  def <= (that: Any): Boolean = (this < that) || (this == that)
  def >  (that: Any): Boolean = !(this <= that)
  def >= (that: Any): Boolean = !(this < that)

The type Any which is used above is the type which is a super-type of all other types in Scala.

Let’s define a Date class representing date:

class Date(y: Int, m: Int, d: Int) extends Ord {
  def year = y
  def month = m
  def day = d

  override def toString(): String = year + "-" + month + "-" + day

  override def equals(that: Any) : Boolean =
    that.isInstanceOf[Date] && {
      val o = that.asInstanceOf[Date] == day && o.month == month && o.year == year

  def < (that: Any): Boolean = {
    if (!that.isInstanceOf[Date])
      error("cannot compare " + that + " and Date")

    val o = that.asInstanceOf[Date]
    (year < o.year) ||
    (year == o.year && (month < o.month ||
                        month == o.month && day <

The last method to define is the predicate which tests for inferiority. It makes use of a predefined method, error, which throws an exception with the given error message.

Installing Scala

To install Scala is pretty simple. First you need to download Scala from

Then unpack the Scala installation file and set the environment variables:

Environment Variable Value
Windows %SCALA_HOME%

Run it interactively

The scala command starts an interactive shell where Scala expressions are interpreted interactively.

> scala
  This is a Scala shell.
  Type in expressions to have them evaluated.
  Type :help for more information.

  scala> object HelloWorld {
       |   def main(args: Array[String]) {
       |     println("Hello, world!")
       |   }
       | }
  defined module HelloWorld

  scala> HelloWorld.main(null)
  Hello, world!
  unnamed0: Unit = ()

Compile it

The scalac command compiles Scala source files and generates Java bytecode which can be executed on any standart JVM

> scalac HelloWorld.scala

Execute it

The scala command executes the generated bytecode with the appropriate options:

> scala -classpath . HelloWorld

The Hello World Program

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello World!")

If the object extends Application, then all the statements contained in that object will be executed, so we don’t need a main method:

object HelloWorld extends Application {
  println("Hello World")

Here is another HelloWorld example in Scala:

object HelloWorld extends Application {
  for(i<-List("olleH", " ", "!dlrow")) {

I intend to write more about Scala here, but if you want to lean more right now go to Scala site:

That’s all folks!


Installing JRuby on Ubuntu

Today we will see how to install JRuby on Ubuntu

First of all you need to download the JRuby. Download the latest JRuby accessing the link:

I am using the version 1.3.1 (jruby-bin-1.3.1.tar.gz)

Open a terminal and go to the directory where you have downloaded file and unpack the jruby file using the following command:

$ tar zxvf jruby-bin-1.3.1.tar.gz

We need to set some environment variables. I will add the following line at end of file .bashrc in your home directory.

export JRUBY_HOME=/home/leonardo/jruby-1.3.1

Now, Let’s check whether JRuby is installed properly, type the command:

$ jruby -v

You should see something like this:

jruby 1.3.1 (ruby 1.8.6p287) (2009-06-15 2fd6c3d) (Java HotSpot(TM) Client VM 1.6.0_13) [i386-java]

Alright! If you are able to see the JRuby version, your system is configured properly.

Now you can start installing some gems:

$ jruby -S gem install jruby-openssl

jruby-openssl is necessary due JRuby doesn’t support the default Ruby’s openssl.

The parameter -S tells JRuby to use the scripts which are in JRuby’s bin directory, then in a second case to use the which ones in the system PATH.

If you want to install Rails:

$ jruby -S gem install rails

That’s all about!

Installing Ruby on Ubuntu

This post will teach you how to install the Ruby on Ubuntu.

So, open your terminal and type the following commands:

$ sudo apt-get install ruby1.8 ruby1.8-dev irb1.8 rdoc1.8 ri1.8

Now, lets install RubyGems:

$ wget
$ tar xvzf rubygems-1.3.4.tgz
$ cd rubygems-1.3.4
$ sudo ruby1.8 setup.rb

The above command will install the RubyGems version 1.3.4

Lets now create some links to make the use of Ruby easy:

$ sudo ln -s /usr/bin/gem1.8 /usr/bin/gem
$ sudo ln -s /usr/bin/ruby1.8 /usr/bin/ruby
$ sudo ln -s /usr/bin/rdoc1.8 /usr/bin/rdoc
$ sudo ln -s /usr/bin/ri1.8 /usr/bin/ri
$ sudo ln -s /usr/bin/irb1.8 /usr/bin/irb

That’s all! Now you can start using Ruby!

I will teach you how to install Rails on the next post.

All the best,


Semana de Palestras

Essa semana que passou foi a semana das palestras. Quinta-feria passada dia 23, eu estive na ETEC de Vargem Grande do Sul apresentando uma palestra sobre Tecnologia Java. Tivemos um auditório lotado e parece que o pessoal gostou. Agradeço a todos da ETEC de Vargem Grande do Sul pela oportunidade e também pela participação dos alunos.

Na última sexta-feira, dia 24, foi um dia da minha apresentação sobre JRuby on Rails. Na verdade foi uma sessão técnica onde eu mostrei como fazer uma aplicação usando JRuby e Rails e depois usando Warbler para empacotar a aplicação e fazer o deployment no Glassfish. Também foi muito bacana mostrar para o pessoal como Rails é produtivo e fácil e o mais importante mostrar que é possível através do JRuby usar todos os recursos de uma plataforma Java. Obrigado ao pessoal que esteve presente na apresentação.



Café com TOM


Ontem eu assisti excelentes palestras on-line do Café com TOM. Para quem não conhece o Café com TOM é o oferecido gratuitamente pela e-Genial. Se você não pode acompanhar as palestras on-line, você pode baixar a gravação delas quando quiser, é o que eu geralmente faço. Posso dizer que a qualidade da gravação é muito boa.

Alias o Café com TOM usa o Treina TOM, uma excelente ferramenta colaborativa de ensino a distância, desenvolvida pelo própria e-Genial.

Gostaria de parabenizar a e-Genial por esse magnífico trabalho com o Treina TOM e Café com TOM.

Bom pra finalizar, não deixem de conferir as palestras do Café com TOM. Lá você irá encontrar palestras de RSpec, Merb, BlazeDS, entre outras.



Sun Certified Developer for Java Web Services 5.0 Results

Hi All,

Today I am very happy to inform that I got the Sun Certified Developer for Java Web Services 5.0.

After a hard study and a very stressed exam test with 150 questions I got this good news. Looks our Study Group worked!

I really thought that I would not get this result since I thought the exam very hard, but everything went well.

Have a nice day,

Leo (SCDJWS 5.0)

Transaction strategies


I’ve just read a very interesting article in DeveloperWorks about Transaction strategies to avoid some common transaction pitfalls. I thought that very useful to understand how transactions work in EJB3 and Spring Framework.

Take a look at that:

Transaction strategies: Understanding transaction pitfalls

All the best,


DB2: First day of month and Last day of month

Hi Guys,

That’s a very simple tip but may be useful sometimes.

In Db2 database how to get the first day of current month for example?

You can do something like this:

select current date + 1 days - day(current date) days
from schema.table_name

Or, how to get the last day of the current month?

Doing something like this:

select current date + 1 month - day(current date + 1 month) days
from schema.table_name

I don’t know if that is the best solution but that’s already save me. If you know a better solution, please let me know.

All the best,


Rails + Merb = Rails 3

Yeah! That’s right. Rails and Merb has joined as announced here.

On December 23rd, they decided to end the duplication and the paradox of choice and announced the commitment to work together bringing the best ideas of Merb to Rails 3.

I think that’s amazing for all of us developers! A great Christmas gift!

My best wishes of Merry Christmas for every one!

SCDJWS 5.0 My Study Notes

Hello Folks!

Yesterday I finished doing my notes for the SCDJWS 5.0 Beta exam. It’s a lot of stuffs to study and my test is coming (next week). I prepared a document with some information I found on the internet. There so many sources. The document is not 100% covering the exam, but it has a lot of information that will help you on your studying.

As a good person! 😀 I will share with you this material. You can download it from here.

Good Study and Good Luck on the test!

Have a nice week!