Scala statements
If you have a good understanding of Java language, then it will be easy to learn Scala. The biggest syntax difference between Scala and Java is that line terminators are optional. Consider a Scala program which can be defined as a collection of objects that communicate by calling each other's methods. Now, briefly look at what are called classes, objects, methods and temporary variables.
Objects - Objects have state and behavior. For example: a dog has states - color, name, breed, and it has behaviors - wag, bark, eat. An object is an instance of a class.
Class - A class can be defined as a template/blueprint to describe behavior/indicate its type of supporting objects.
Method - A method is essentially an action. Classes can contain many methods. It is in the method where the logic is written, the data is manipulated and all actions are performed.
Fields − Every object has its unique set of temporary variables, which are called fields. The object's state is created by the values assigned to these fields.
The first Scala program:
Interactive mode programming:
Calling the interpreter without passing a script file as a parameter will display the following prompt:
C:>scalaWelcome to Scala version 2.9.0.1Type in expressions to have them evaluated.Type :help for more information.scala>
Type the following text into the Scala prompt and press Enter:
scala> println("Hello, Scala!");
This will produce the following results:
Hello, Scala!
Script mode programming:
Let's look at a simple code that prints a simple sentence: Hello, World!
object HelloWorld { /* This is my first java program. * This will print 'Hello World' as the output */ def main(args: Array[String]) { println("Hello, world!") // prints Hello World }}
Let's see how to save the file, compile and run the program. Please follow the steps below:
Open notepad and add the above code.
Save the file as: HelloWorld.scala.
Open a command prompt window and change to the directory where you saved the program files. Let's say it's C:>
- ## Type "scalac HelloWorld.scala" and press Enter to compile the code. If there are no errors in the code, the command prompt will automatically wrap to the next line.
The above command will generate several class files in the current directory. One of the names is HelloWorld.class. This is a bytecode that can be run on the Java Virtual Machine (JVM).
Now, type "scala HelloWorld" to run the program.
You can see "Hello, World!" printed on the window.
C:> scalac HelloWorld.scala C:> scala HelloWorldHello, World!
Basic grammar
Regarding Scala programs, it is very important to pay attention to the following points.
Case sensitivity - Scala is case sensitive, which means that the identifiers Hello and hello will have different meanings in Scala.
Class Name - Capitalize the first letter of all class names.
If you need to use several words to form a class name, capitalize the first letter of each word.
Example: class MyFirstScalaClassMethod Name - The first letter of all method names is lowercase.
If several words are used to form the name of a method, the first letter of each word should be capitalized.
Example: def myMethodName()Program File Name - The name of the program file should exactly match the object name.
When saving the file, you should save it using the object name (remember Scala is case sensitive) and append ".scala" as the file extension. (If the file name and object name do not match, the program will not compile).
Example: Assume "HelloWorld" is the name of the object. Then the file should be saved as 'HelloWorld.scala"def main(args: Array[String]) - The Scala program starts processing from the main() method, This is the mandatory program entry part of every Scala program
age, salary, _value, __1_valueThe following are illegal identifiers:
$salary, 123abc, -salary
Operator identifier
An operator identifier consists of one or more operator characters. Operation characters are printable ASCII characters such as +, :, ?, ~ or #. The following are legal operator identifiers:
+ ++ ::: <?> :>
The Scala compiler will internally "roll" operator identifiers so that they become legal Java identifiers, embedding the $ character. For example, the identifier:-> will be represented internally as $colon$minus$greater.
Mixed identifier
Mixed identifiers are identified by an alphanumeric identifier, followed by an underscore and operator. The following are legal mixed identifiers:
unary_+, myvar_=
Here, unary_+ is used as a method name to define a unary + operator and myvar_= is used as a method name to define an assignment operator.
Immediate data identifier
A literal identifier is any string of characters enclosed in backticks (` . . . `). The following are legal text identifiers:
`x` `<clinit>` `yield`
Scala keywords:
The following list shows the reserved words in Scala. These reserved keywords may not be used as constants or variables, or any other identifier names.
abstract | case | catch | class |
def | do | else | extends |
false | final | finally | for |
forSome | if | implicit | import |
lazy | match | new | null |
object | override | package | private |
protected | return | sealed | super |
this | throw | trait | try |
true | type | val | var |
while | with | yield | |
- | : | = | => |
<- | <: | <% | >: |
# @ |
Comments in Scala
Scala supports single-line and multi-line comments much like Java. Multi-line comments can be nested, but they must be nested correctly. Any comments and all characters available will be ignored by the Scala compiler.
object HelloWorld { /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ def main(args: Array[String]) { // Prints Hello World // This is also an example of single line comment. println("Hello, world!") }}
Blank lines and spaces:
A line containing only whitespace, possibly with a comment, is called a blank line, and Scala will ignore it entirely. Tags can be separated by spaces and/or comments.
Line break:
Scala is a line-oriented language, and statements can be terminated with a semicolon (;) or a newline character. A semicolon at the end of a statement is usually optional. You can type a desired statement if it appears on a line by itself. On the other hand, if you write multiple statements in one line a semicolon is required:
val s = "hello"; println(s)
Scala package:
A package is a code-named module. For example, the Lift utility package net.liftweb.util. The package declaration is the first non-comment line in the source file, as shown below:
package com.liftcode.stuff
Scala packages can be imported, enabling them to be referenced within the current compilation scope. The following statement is the content of the scala.xml package imported:
import scala.xml._
Encapsulated classes and objects can be imported, for example, HashMap from scala.collection.mutable:
import scala.collection.mutable.HashMap
Multiple classes or objects can be imported from a single encapsulated scala.collection.immutable package, for example, TreeMap and TreeSet:
import scala.collection.immutable.{TreeMap, TreeSet}