In our last Scala tutorial we have seen how we install Scala on CentOS Linux using the rpm package provided by www.scala-lang.org. If you have not done it yet feel free to follow the tutorial here - How to install Scala in CentOS.
I am not going to go over how great and why you should learn Scala bla bla bla ..... because who is looking to learn Scala he already has something in mind, So let us jump into it.
If you are familiar with Java then you will pickup Scala with ease, both languages are similar.
Scala programming can be defined as a collection of objects that communicate by invoking each other’s methods.
Here is the list of objects and their definition:
Objects have states and behaviors. An object is an instance of a class.
Example − A car has states - color, name, brand as well as behaviors - drive,stop,start.
A class can be defined as a template that describes the states that are related to the class.
A method is basically a behavior. A class can contain many methods. It is in methods where the logic are written, data is manipulated and all the actions are executed.
Each object has its unique set of instant variables, which are called fields.
A closure is a function, whose return value depends on the value of one or more variables declared outside this function.
A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods.
Lets write the first line of code in Scala:
open you Scala shell
in Scala shell we can complete the commands by using the tab key (tab completion).
So as you could see we just wrote our first line of Scala code, nothing much but printing a line "Printed in Scala".
Now let us see how we implement this in a Scala script compile and run it in Scala
will create file called script.scala
Compile and execute:
The scalac command is used to compile the Scala program and it will generate a few class files in the current directory.
One of them will be called ScalaTest.class and is a bytecode which will run on Java Virtual Machine (JVM) using scala command.
Ok , we just dipped into Scala programming and in the next tutorial we will see what is the Syntax used in Scala.